前後端互動時有時需要對介面返回的物件做一些統一的處理,這時就可以實現ResponseBodyAdvice介面進行自定義處理。
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
@SneakyThrows
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// 將boday轉換成返回的物件
Res res = (Res)body;
// 操作返回物件的值
res.setCustomizeCode(123456);
return body;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結