一个技术需求引发的思考和实践:
public interface RequestBodyAdvice
public interface RequestBodyAdvice {
// 什么时候切
boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType);
// 切到读body前的位置
HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
// 切到读body后的位置
Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
// 处理空body
@Nullable
Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
}
根据接口描述,直接实现这个接口需要读很多参数的含义,其实实现业务需求仅需要:
RequestBodyAdviceAdapter
该适配器简化了一个方法,并提供了必要的三个方法的实现
public abstract class RequestBodyAdviceAdapter implements RequestBodyAdvice {
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
throws IOException {
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
@Nullable
public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
}
根据适配器描述 afterBodyRead
方法能获取到 body
参数,我们能找到重点
afterBodyRead
方法afterBodyRead
方法的 body
参数public abstract class AdviceAdapter extends RequestBodyAdviceAdapter {
// 暴露关心的参数
abstract void validate(Object body);
@Override
public boolean supports(MethodParameter methodParameter, @Nullable Type targetType, @Nullable Class<? extends HttpMessageConverter<?>> converterType) {
return Objects.nonNull(methodParameter.getMethodAnnotation(RequestValidated.class));
}
@Override
@Nonnull
public Object afterBodyRead(@Nonnull Object body, @Nullable HttpInputMessage inputMessage, MethodParameter parameter,
@Nullable Type targetType, @Nullable Class<? extends HttpMessageConverter<?>> converterType) {
// 嵌入切面
validate(body);
return input;
}
}
// 注意切 RequestBody 用的注解是 ControllerAdvice
@ControllerAdvice
public class ValidateAdvice extends AdviceAdapter {
// 具体实现
@Override
void validate(Object json) {
}
}