老项目改造返回值规范化


背景:

已经运行的项目,开始由于赶工期等因素,未做统一的接口返回规范。现在要做规范化,还必须要保留原先的接口,尤其是APP的接口,有的版本会存在一个比较长的时间。因此需要保留两个版本,又不想维护两套代码。

使用ResponseBodyAdvice拦截获取controller的responsebody内容

basePackages指定需要拦截的包supports返回是否需要拦截通过返回类型、请求路径匹配、header中的参数值等过滤请求内容,然后重写返回对象,返回值。

@Slf4j@ControllerAdvice(basePackages="")publicclassApiResponseBodyAdviceimplementsResponseBodyAdvice{@Overridepublicbooleansupports(MethodParametermethodParameter,ClassconverterType){//可以过滤拦截哪些内容比如方法类型booleansupported=().getReturnType().equals();returntrue;}@OverridepublicObjectbeforeBodyWrite(Objectbody,MethodParametermethodParameter,MediaTypeselectedContentType,ClassselectedConverterType,ServerHttpRequestrequest,ServerHttpResponseresponse){Stringpath=().getPath();StringklassMethod=().getDeclaringClass().getName()+"#"+().getName();("requesturi:{}method:{}",path,klassMethod);if(bodyinstanceofString){Resultresult=newResult(200,"success",body);(result);}if(!(bodyinstanceofResult)){returnbody;}Resultresult=(Result)body;//通过Path匹配,或者header中的值来过滤请求AntPathMatcherpathMatcher=newAntPathMatcher();booleanmatched=("/api/newUri/**",path);("pathmatch{}{}",path,matched);if(matched){//重写返回码(newCode);}//生成新的规范化转码newCode//(newCode);returnresult;}}
@DatapublicclassResultT{privateIntegercode;privateStringmessage;privateObjectcontent;publicResult(){}publicResult(Integercode,Stringmessage,Objectcontent){=code;=message;=content;}}

测试请求,对/resCode请求拦截后重写返回对象,对返回类型为Result重写规范化后的值setCode,setMessage.

@RestControllerpublicclassResController{@GetMapping("/resCode")publicObjectresCode(){return"thisisresponsedata";}@GetMapping("/standardResCode")publicResultstandardResCode(){returnnewResult(200,"Success","standardResCode");}}

访问http://localhost:8080/resCode返回

{"code":200,"message":"success","content":"thisisresponsedata"}
方式二通过拦截器Interceptor或者自定义Aop拦截重设返回值。

项目中一般会为某个业务分配一个值段如810xxx,每个业务定义一个枚举存放返回值code、message.

版权声明:本站所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请举报,一经查实,本站将立刻删除。

相关推荐