使用注解@RestControllerAdvice
新建自定义类:
/**
* desc
*
* @author cjq
* @date 2022/10/11
*/
@RestControllerAdvice(value={"com.xxx.sjcj"},annotations = {ResultWrapper.class})
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
SjcjResponse res = new SjcjResponse();
JSONObject bodyObj = JSONObject.parseObject(JSON.toJSONString(body));
int code = bodyObj.getInteger("code");
if(HttpStatus.SUCCESS!=code){
res.setCode(RespEnum.UNKNOW_ERROR.getCod());
res.setDes(bodyObj.getString("msg"));
}
return res.toString();
}
}
在需要重构返回体的方法上加注解ResultWrapper
ResultWrapper类:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResultWrapper {
}
使用在方法中:
@PostMapping
@ResultWrapper
public AjaxResult addBatch(@RequestBody List<SjcjSyfwEntity> list){
//... 省略
}