实践spring自定义返回格式
2020-08-20 本文已影响0人
栗津津家的栗冬冬
step 1 查看springmvc下的一些处理器解释器:
下面以RequestResponseBodyMethodProcessor为例

step2 :
查看接口继承实现关系
RequestResponseBodyMethodProcessor----->AbstractMessageConverterMethodProcessor---->HandlerMethodReturnValueHandler


HandlerMethodReturnValueHandler为顶层接口,需要去实现这两个方法。
查看RequestResponseBodyMethodProcessor具体实现如下:


具体处理如下:

以其中一个实现为例:
在MappingJackson2Http没有看到write的实现则往上层找找看

AbstractJackson2HttpMessageConverter中的write

至此,RequestResponseBodyMethodProcessor的处理返回值流程完毕,那么我们来自己实现下自定义的返回体。
仿照RequestResponseBodyMethodProcessor来试试看
首先我们根据上面源码可知,通过一些方法上的注解可以来判断是否支持处理返回值,那么我们自定义一个annotation interface

自定义封装格式类

自己定义一个处理器来复写RequestResponseBodyMethodProcessor处理器的处理条件和处理方式

向注册自己的处理器

启动下项目找个接口试试看是否能成功
1、添加注解返回:

2、注释注解则不回去处理格式

结果ok