BodyAdvice用处:
- 参数过滤
- 字符的编码
- 第三方的加解密
RequestBodyAdvice:
作用:进行统一接口请求参数处理
优势:全局解决方案,使原本在Controller处理的内容统一全局处理,精简代码量、降低耦合度。
官方API解读:
Allows customizing the request before its body is read and converted into an Object and also allows for processing of the resulting Object before it is passed into a controller method as an @RequestBody
or an HttpEntity
method argument.
Implementations of this contract may be registered directly with the RequestMappingHandlerAdapter
or more likely annotated with @ControllerAdvice
in which case they are auto-detected.
允许在请求体被读取并转换为对象之前自定义请求,也允许在结果对象作为@RequestBody或HttpEntity方法参数传递给控制器方法之前处理结果对象。
这个契约的实现可以直接注册到RequestMappingHandlerAdapter,或者更有可能用@ControllerAdvice注解,在这种情况下,它们会被自动检测到。
RequestBodyAdvice仅对使用了@RqestBody注解的生效 , 因为它原理上还是AOP , 所以GET方法是不会操作的.
ResponseBodyAdvice
作用:进行统一接口返回数据处理
优势: 需要对返回接口数据进行二次包装处理返回体,如修改返回值、数据加密。
官方API解读:
Allows customizing the response after the execution of an @ResponseBody
or a ResponseEntity
controller method but before the body is written with an HttpMessageConverter
.
Implementations may be registered directly with RequestMappingHandlerAdapter
and ExceptionHandlerExceptionResolver
or more likely annotated with @ControllerAdvice
in which case they will be auto-detected by both.
允许在@ResponseBody或ResponseEntity控制器方法执行之后,但使用HttpMessageConverter编写主体之前自定义响应。
实现可以直接用RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver注册,或者更可能用@ControllerAdvice注释,在这种情况下,它们都将被自动检测到。
具体使用方式可以参考我的开源项目