栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring响应数据再处理(spring统一处理)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring响应数据再处理(spring统一处理)

在开发过程中有时候我们需要对响应的数据进行再封装,但是前面已经写了很多的响应信息,修改起来工作量巨大且可能会遗漏。这时候我们就可以使用返回值统一进行处理。比如直接封装到result中。

我们可以使用@ControllerAdvice并实现ResponseBodyAdvice对每个接口的进行处理。

我本次演示是自定义一个注解@Zhu,如果类或者方法上加上了这个注解就进行处理。当supports方法返回的是true的时候,才会执行beforeBodyWrite方法;可以进行返回值的判断,进行相应的处理。

自定义注解如下:

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Zhu {
}

如何检测出注解:

获取返回方法上是否有zhu注解
returnType.getMethodAnnotation(Zhu.class) != null
查找类中,是否涵盖Zhu注解。如果有,就返回此注解,没有就返回空(类上的联合注解也可检测出)
AnnotationUtils.findAnnotation(returnType.getContainingClass(),
获取返回类上是否有zhu注解
returnType.getContainingClass().isAnnotationPresent(Zhu.class)

下面是实现代码:

@Configuration
public class WebConfig {

    
    @ControllerAdvice
    static class MyControllerAdvice implements ResponseBodyAdvice {
        // 满足条件才转换
        public boolean supports(MethodParameter returnType, Class> converterType) {
            
            if (returnType.getMethodAnnotation(Zhu.class) != null ||
                AnnotationUtils.findAnnotation(returnType.getContainingClass(), Zhu.class) != null) {
//                returnType.getContainingClass().isAnnotationPresent(Zhu.class)) {
                return true;
            }
            return false;
        }

        // 将返回值进行响应的处理
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
            if (null == body) {
                return body + ";返回为null";
            }
            if (body instanceof Integer) {
                return body + ";返回成功==Integer";
            }

            if (body instanceof String) {
                return body + ";返回成功==String";
            }
            return "Result.ok(body)";
        }
    }
}
 

平时进行统一处理返回值的相关业务可以直接使用。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号