你可能会有这样的需求,对你的Controller返回值进行一个二次封装,
如下:code是结果码(1、成功,0、失败,2、未登录...),data为携带数据
{"code":"1","data":{"name":"xiaoming","age":"30"}}
因为SpringBoot默认的ResponseBody的处理程序就是HandlerMethodReturnValueHandler,所以我们自己写的HandlerMethodReturnValueHandler通常无法生效,
非要使用HandlerMethodReturnValueHandler,那么只能替换掉默认的,
如果只是想对Controller的所有返回值进行封装,产生上面的效果,使用ResponseBodyAdvice会更加简单一些,下面几行代码就足够了
import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import java.util.HashMap; import java.util.Map; /** * Created by 12614 on 2018/5/11. */ @ControllerAdvice public class TestResponseAdvice implements ResponseBodyAdvice<Object>{ @Override public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) { return methodParameter.hasMethodAnnotation(ResponseBody.class); } @Override public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { Map<String,Object> res = new HashMap<>(); res.put("code","1"); res.put("data",o); return res; } }