Spring AOP execution表达式,拦截 参数被注解注释了的方法

问题描述:

       项目中碰到一个需求,希望所有“存在参数被自定义注解@RequestModel注释”了的方法都被切面拦截,在实际逻辑执行前,先进行参数验证。

    @RequestMapping(value = "list", method = {RequestMethod.GET})
    public ResultModel list(@RequestModel RoleListReq roleListReq) {
        // 希望在下面代码执行前,先对 roleListReq 实体中的属性进行参数校验
        try {
            // do something
            return SUCCESS;
        } catch (Exception e) {
            logger.error("Error!", e);
        }
        return FAILED;
    }

Ps:@RequestModel为自定义的一个注解,功能类似@RequestBody,其作用为“将GET方式请求过来的参数封装为一个实体”。

       在网上百度了很久,查阅了官方文档,实在是不知道这个execution表达式该怎么写。

       查了一些资料,发现了@annotation这个注解。部分网友的博文中,有些描述的不够清楚,有的是机械地进行了单词直译,看了以后反而被误导了。@annotation注解的用处参考本文参考文献的第三条链接中 kriegaex 的回答。下图贴出来了,方便网络不好的朋友。

       知道不能用@annotation这个注解后,弃用百度,开始Google,一下子就找到了。在Spring官方的论坛中,找到了答案。最终参考下图红色方框中的写法。

      这里,贴上本项目中我的 execution表达式 的写法:

    @Around("execution(* com.xxx.*.*(@com.xxx.RequestModel (*), ..))")
    public Object validate(ProceedingJoinPoint pjp) throws Throwable {
        Object args = pjp.getArgs()[0];
        Object resultModel;
        BeanPropertyBindingResult result = new BeanPropertyBindingResult(args, args.getClass().getName());
        validator.validate(args, result);
        if (result.hasErrors()) {
            return new ResultModel(ResultCode.CODE_00003.getCode(), result.getAllErrors().get(0).getDefaultMessage());
        } else {
            resultModel = pjp.proceed();
        }
        return resultModel;
    }

       如果有哪儿我没有表述清楚的,欢迎一起交流。若有纰漏,欢迎指出,一起进步!

 

参考文献:

1、https://docs.spring.io/spring/docs/4.3.19.RELEASE/spring-framework-reference/htmlsingle/#aop

2、https://blog.csdn.net/michel27/article/details/38584883

3、https://stackoverflow.com/questions/16810617/aspectj-java-instrumentation-to-intercept-an-annoted-parameter-call-usage

4、http://forum.spring.io/forum/spring-projects/aop/81236-pointcut-matching-methods-with-annotated-parameters

5、https://www.cnblogs.com/yanjunwu/p/3996570.html

 

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值