springboot接口自定义返回包装数据
1:springboot web项目接口返回是基本对象类型,现在封装返回对象数据
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor#handleReturnValue
这个类处理接口返回数据,所以新增实现HandlerMethodReturnValueHandler类,在默认处理handler之前,就可以处理接口返回值增加封装类
下面是具体实现
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请求
github代码地址 https://github.com/knowledgeAlan/trail-excise-demo/tree/customer-response-format