在 spring 中提供了个 ResponseBodyAdvice 接口,可以帮助我们将返回的值进行统一封装,代码如下
@ControllerAdvice
@Slf4j
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
log.debug("MyResponseBodyAdvice==>supports:" + converterType);
log.debug("MyResponseBodyAdvice==>supports:" + returnType.getClass());
log.debug("MyResponseBodyAdvice==>supports:" + MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType));
return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
if (body == null) {
return Result.success();
}
if (body instanceof Result || body instanceof File || body instanceof ResponseEntity) {
return body;
} else {
log.debug("MyResponseBodyAdvice==>beforeBodyWrite:" + returnType + "," + body);
return Result.success(body);
}
}
}
但是现在有个问题就是,一些第三方组件也使用 json 通信,比如 swagger。这时候就需要排除这些东西,或者是指定切面才进行统一封装。
请问 V 友们应该怎么做,可以不用 ResponseBodyAdvice 接口
1
YzSama 2018-12-27 23:13:52 +08:00 via iPad
注解
|
2
skypyb 2018-12-27 23:24:40 +08:00 via Android
注解确实可以。
|
4
zhazi 2018-12-29 06:08:18 +08:00 via Android
自己写一个注解 在 supports 里控制
|
6
joenali 2019-07-23 16:12:37 +08:00 1
注意 @ControllerAdvice 这个注解可以指定 basePackages,只作用业务的 controller,如:
@ControllerAdvice(basePackages = "com.xxxx.controller") |