使用ControllerAdvice注解来进行全局数据处理

@ControllerAdvice ,这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:

全局异常处理
全局数据绑定
全局数据预处理

处理所有controller返回的数据

//定义一个全局的响应
//@ControllerAdvice,所有的Controller只要执行,这个地方就会得到通知
@ControllerAdvice(value = {"com.hubu.controller"})
public class GlobalResponse implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        //获取当所执行的Controller对象的class类型的对象,它是整个反射的入口,通过class类型的对象我们拿到一切的对象
        Class<? extends Executable> clazz = returnType.getExecutable().getClass();
        //获取类头顶的@IgnoreWrapper这个注解,但是用户可能没有加上
        IgnoreWrapper annotation = clazz.getAnnotation(IgnoreWrapper.class);
        if (null == annotation){
            //这里其实就是拿Method类型的对象,Method继承了Executable
            Executable executable = returnType.getExecutable();
            IgnoreWrapper iw = executable.getAnnotation(IgnoreWrapper.class);
            if (null == iw){
                return true; //进入beforeBodyWrite方法
            }
            return false;
        }else {
            return false;  //返回false,不会对我们的返回值进行二次包装
        }
    }

    //我们需要关注的是该方法的返回值类型,第一个参数是controller的返回值
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        /**
         * 目的:当Controller中方法的返回值是Result,就没有必要通过Result进行封装了*
         */
        Method method = (Method) returnType.getExecutable();
        if (Result.class == method.getReturnType()){
            return body;
        }
        return Result.buildSuccess(body);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值