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 {

    /**
     * 响应对象再处理
     * supports方法返回ture时才能执行beforeBodyWrite方法
     */
    @ControllerAdvice
    static class MyControllerAdvice implements ResponseBodyAdvice<Object> {
        // 满足条件才转换
        public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
            /**
             * 获取返回方法上是否有zhu注解
             * returnType.getMethodAnnotation(Zhu.class) != null
             *
             * 查找类中,是否涵盖Zhu注解。如果有,就返回此注解,没有就返回空(类上的联合注解也可检测出)
             * AnnotationUtils.findAnnotation(returnType.getContainingClass(), Zhu.class) != null
             *
             * 获取返回类上是否有zhu注解
             * returnType.getContainingClass().isAnnotationPresent(Zhu.class)
             */
            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<? extends HttpMessageConverter<?>> 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)";
        }
    }
}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值