优化请求格式
接口RequestBodyAdvice
使用的步骤:
1、编写一个类,实现RequestBodyAdvice接口
2、在类中实现对应的方法
3、在该实现类上加注解@ControllerAdvice
RequestBodyAdvice接口所提供的方法如下:
boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType);
//该方法返回值为true的时候才才能进入下面的方法
HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
//body数据读取之前调用,一般在在此方法中对body的数据进行修改
Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
afterBodyRead()
Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
当body为空的时候调用该方法
第一个supports方法必须实现,因为只有supports方法返回值为true的时候才能进入下边的,后面的可以选择性实现
优化响应格式
接口ResponseBodyAdvice
可以使用ResponseBodyAdvice对后端返回结果的格式进行统一的定义。
使用的步骤:
1、写一个实现类,实现ResponseBodyAdvice
2、重写ResponseBodyAdvice提供的方法,两个,分别是supports和boforeBodyWrite
3、在该实现类上加注解@ControllerAdvice
ResponseBodyAdvice接口提供的方法:
boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response);
请求和响应的supports方法中有一个参数是MethodParameter,是Spring MVC中的一个类,用于表示控制器方法中的方法参数。该类提供了有关方法其参数的详细信息
-
getMethodAnnotation(Class<A> annotationType)
: 获取参数上指定类型的注解。 -
hasParameterAnnotation(Class<? extends Annotation> annotationType)
: 检查参数是否带有指定类型的注解
通过MethodParameter的这两个方法就可以知道controller方法上是不是有指定的注解了,从而结合自定义注解实现对返回值格式的统一封装
这里可以结合自定义注解来实现对相应格式的定义,supports的判断条件就是接口方法或者类上是否标注了我们自己定义的注解
@ControllerAdvice有一个属性basePackage,可以用来指定特定的包生效,我们把controller接口所在的包配上。就可以实现给所有controller的入参出参指定格式