springboot接口自定義返回包裝數(shù)據(jù)
1:springboot web項(xiàng)目接口返回是基本對(duì)象類型轰绵,現(xiàn)在封裝返回對(duì)象數(shù)據(jù)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor#handleReturnValue
這個(gè)類處理接口返回?cái)?shù)據(jù)粉寞,所以新增實(shí)現(xiàn)HandlerMethodReturnValueHandler類左腔,在默認(rèn)處理handler之前,就可以處理接口返回值增加封裝類
下面是具體實(shí)現(xiàn)
ApiResponseHandlerMethodReturnValueHandler
public class ApiResponseHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
private MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) || returnType.hasMethodAnnotation(ResponseBody.class)
&& ApiResponse.class.equals(returnType.getParameterType()));
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
mavContainer.setRequestHandled(true);
ApiResponse apiResponse = ApiResponse.ok(returnValue);
HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();
response.addHeader("v","3");
ServletServerHttpResponse servletServerHttpResponse =createOutputMessage(webRequest);
converter.write(apiResponse, MediaType.APPLICATION_JSON,servletServerHttpResponse);
}
protected ServletServerHttpResponse createOutputMessage(NativeWebRequest nativeWebRequest){
HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
Assert.state(response!=null,"no HttpServletResponse");
return new ServletServerHttpResponse(response);
}
}
2:配置WebMvcConfiguration
@Configuration
public class WebMvcConfiguration {
@Autowired
public void resetRequestMappingHandlerAdapter(RequestMappingHandlerAdapter requestMappingHandlerAdapter){
List<HandlerMethodReturnValueHandler> handlerMethodReturnValueHandlers = requestMappingHandlerAdapter.getReturnValueHandlers();
List<HandlerMethodReturnValueHandler> newHandlerMethodReturnValueHandlers = new ArrayList(handlerMethodReturnValueHandlers);
newHandlerMethodReturnValueHandlers.add(0,new ApiResponseHandlerMethodReturnValueHandler());
requestMappingHandlerAdapter.setReturnValueHandlers(newHandlerMethodReturnValueHandlers);
}
}
3:postman請(qǐng)求
github代碼地址 https://github.com/knowledgeAlan/trail-excise-demo/tree/customer-response-format