ResponseBodyAdvice的使用
ResponseBodyAdvice 可以在注解 @ResponseBody 将返回值处理成相应格式之前进行操作返回值
ResponseBodyAdvice 对Controller返回 {@code @ResponseBody or a {@code ResponseEntity}} 之后 {@code HttpMessageConverter} 类型转换之前进行拦截,进行相应的操作之后,将结果返回。
ResponseBodyAdvice 源码如下:
/** 数据的处理顺序向下
* Allows customizing the response after the execution of an {@code @ResponseBody}
* or a {@code ResponseEntity} controller method but before the body is written
* with an {@code HttpMessageConverter}.
*
* <p>Implementations may be registered directly with
* {@code RequestMappingHandlerAdapter} and {@code ExceptionHandlerExceptionResolver}
* or more likely annotated with {@code @ControllerAdvice} in which case they
* will be auto-detected by both.
*
* @author Rossen Stoyanchev
* @since 4.1
* @param <T> the body type
*/
public interface ResponseBodyAdvice<T> {
/**
* Whether this component supports the given controller method return type
* and the selected {@code HttpMessageConverter} type.
* @param returnType the return type 方法返回的类型
* @param converterType the selected converter type 参数类型转换
* @return {@code true} if {@link #beforeBodyWrite} should be invoked;
* {@code false} otherwise
* 返回 true 则下面 beforeBodyWrite方法被调用, 否则就不调用下述方法
*/
boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
/**
* Invoked after an {@code HttpMessageConverter} is selected and just before
* its write method is invoked.
* @param body the body to be written
* @param returnType the return type of the controller method
* @param selectedContentType the content type selected through content negotiation
* @param selectedConverterType the converter type selected to write to the response
* @param request the current request
* @param response the current response
* @return the body that was passed in or a modified (possibly new) instance
*/
@Nullable
T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response);
}
下面简单写一个实例:
@RestControllerAdvice("指定包下的类")
public class xxx implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
//判断条件
return 判断条件;
}
@Override
public Object beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof ResponseBody) {
return body;
} else {
return ResponseBody<>(body);
}
}
}