ResponseBodyAdvice
实现 ResponseBodyAdvice 接口,其实是对加了@RestController(也就是@Controller+@ResponseBody)注解的处理器将要返回的值进行增强处理。
其实也就是采用了AOP的思想,对返回值进行一次修改。
public interface ResponseBodyAdvice<T> {
/**
* 返回true才进行织入
*/
boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
/**
* 在HttpMessageConverter的write方法被调用之前调用
*/
@Nullable
T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response);
}
自定义ResponseBodyAdvice
@ControllerAdvice
@Order(Integer.MIN_VALUE)
public class ResultResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
if (Objects.isNull(methodParameter) || Objects.isNull(methodParameter.getMethod())) {
return false;
}
Class<?> returnType = methodParameter.getMethod().getReturnType();
// 只拦截返回类型为 ResultBO 的方法
return returnType == null ? false : ResultBO.class.equals(returnType);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (ResultBO.class.isInstance(body)) {
ResultBO resultBO = (ResultBO)ResultBO.class.cast(body);
if (StringUtils.isEmpty(resultBO.getTraceId())) {
// 添加日志跟踪 traceId
resultBO.setTraceId(MDC.get("X-TraceId"));
}
}
return body;
}
}