- 如果特定业务中需要避免数据被全局响应体处理器封装,可以自定义一个注解作用于方法上,同时在 ResponseBodyAdvice.supports() 中对该注解进行过滤
示例
- IgnoreResponseAdvice.java
@Documented @Inherited @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface IgnoreResponseAdvice {
}
|
- GlobalResponseBodyAdvice.java
@RestControllerAdvice public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Resource private ObjectMapper objectMapper;
@Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return !returnType.hasMethodAnnotation(IgnoreResponse.class); }
@SneakyThrows @Override public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { //单字符串处理 if (o instanceof String) { return objectMapper.writeValueAsString(Result.success(o)); } //兼容手动封装 if (o instanceof Result || o instanceof ErrorResult) { return o; } return Result.success(o); } } |
- 在控制层的指定方法上使用此注解,返回值就可以防止被全局响应体封装
示例
@RestController @RequestMapping("/user") public class UserController {
@IgnoreResponse @GetMapping("/{id}") public User getUserById(@PathVariable Integer id) { User user = userService.getById(id); return user; } } |
接口数据返回如下: