1.问题分析
实现ResponseBodyAdvice接口,同时使用RestController,统一后端返回给前端的数据的格式。
/**
* @author:ZhangHaiXia
* @Date: 2022/3/9
* @Description: 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}.
*/
@RestControllerAdvice(annotations = RestResponse.class)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private ObjectMapper objectMapper;
/**
* 这个方法表示对于哪些请求要执行beforeBodyWrite,返回true执行,返回false不执行。
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
if(body instanceof String){
//这段代码一定要加,如果Controller直接返回String的话,SpringBoot是直接返回,故我们需要手动转换成json。
return objectMapper.writeValueAsString(ResultData.success(body));
}
return ResultData.success(body);
}
}
debug:
可以知道:访问swagger-ui.html 的时候,会通过ApiResourceController拿到需要的东西;这里由于对结果做了一层封装;swagger的前端页面无法正常解析;因此报错。
2.解决方案
2.1 方案一
修改supports方法,不对swagger的方法进行处理。
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
@Autowired
private ObjectMapper objectMapper;
/**
* 这个方法表示对于哪些请求要执行beforeBodyWrite,返回true执行,返回false不执行。
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return !returnType.getDeclaringClass().getName().contains("springfox");
}
/**
* 对返回的结果进行封装
*/
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
if(body instanceof String){
//这段代码一定要加,如果Controller直接返回String的话,SpringBoot是直接返回,故我们需要手动转换成json。
return objectMapper.writeValueAsString(ResultData.success(body));
}
return ResultData.success(body);
}
}
2.2 方案二
- 编写一个组合注解,@RestResponse,替代RestController
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD})
@Documented
@RestController
public @interface RestResponse {
}
- 在ResponseBodyAdvice实现类上设置被@RestResponse标注对的controller需要进行处理
@RestControllerAdvice(annotations = RestResponse.class)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
2.3. 方案三
使用basePackages来限制要扫描的包。
@RestControllerAdvice(basePackages = "com.zhx.controller")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
2.4 其他
@RestControllerAdvice
中还有其他的方法能得到一样的效果