ResponseBody、RequestBodyAdvice解读

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注释,在这种情况下,它们都将被自动检测到。

具体使用方式可以参考我的开源项目

eshare

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值