Spring AOP execution表达式,拦截 参数被注解注释了的方法 您所在的位置:网站首页 @around参数 Spring AOP execution表达式,拦截 参数被注解注释了的方法

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

2024-06-08 22:14| 来源: 网络整理| 查看: 265

问题描述:

       项目中碰到一个需求,希望所有“存在参数被自定义注解@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

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有