博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring框架根据传入参数动态的修改注解属性的值
阅读量:4684 次
发布时间:2019-06-09

本文共 1396 字,大约阅读时间需要 4 分钟。

由于业务需要,需要在自定义注解中将参数中的值传入到注解的指定属性中,这很容易让我联想到 Spring 的 SpEL. 虽然根据反射也能得到相同结果,但是有更好的工具为什么不用呢?因此根据网上大神的攻略,整合出模拟版的 SpEL 使用.

  • 开发环境 JDK1.8
  • spring版本 5.0.6.RELEASE

POM引入

org.aspectj
aspectjweaver
1.8.13
org.springframework
spring-expression
5.0.6.RELEASE

这里我引入的是 spring boot的相关版本,为了具有通用性, 因此精确到实际使用的引入和版本

主要代码片段

@AfterReturning(value = "@annotation(primaryKey)")public void doAfter(JoinPoint joinPoint, PrimaryKey primaryKey) throws Exception {    ExpressionParser parser=new SpelExpressionParser();    EvaluationContext ctx = new StandardEvaluationContext();        //获取方法的参数名和参数值    Signature signature = joinPoint.getSignature();    MethodSignature methodSignature = (MethodSignature) signature;    List
paramNameList = Arrays.asList(methodSignature.getParameterNames()); List
paramList = Arrays.asList(joinPoint.getArgs()); //将方法的参数名和参数值一一对应的放入上下文中 for (int i = 0; i < paramNameList.size(); i++) { ctx.setVariable(paramNameList.get(i), paramList.get(i)); } //解析SpEL表达式获取值 String value = parser.parseExpression(primaryKey.primaryKey()).getValue(ctx).toString(); //解析后的业务代码 ...}

这个地方,我是在方法执行完毕后的切面中进行操作, 可以根据业务需要自行决定在哪里使用. 代码中的 primaryKey.primaryKey() 分别是我所自定义的注解名和注解属性d

转载于:https://www.cnblogs.com/cbzj/p/9446864.html

你可能感兴趣的文章
润乾报表 动态控制文本的显示
查看>>
[oracle] 如何使用myBatis在数据库中插入数据并返回主键
查看>>
PHP echo 和 print 语句
查看>>
第一讲 一个简单的Qt程序分析
查看>>
Centos 6.5下的OPENJDK卸载和SUN的JDK安装、环境变量配置
查看>>
poj 1979 Red and Black(dfs)
查看>>
【.Net基础03】HttpWebRequest模拟浏览器登陆
查看>>
UML-画类图与交互图的顺序
查看>>
6月7 考试系统
查看>>
mysql 基本操作
查看>>
zTree async 动态参数处理
查看>>
Oracle学习之常见错误整理
查看>>
HTC Sensation G14开盒
查看>>
lock_sga引起的ksvcreate :process(m000) creation failed
查看>>
数据库插入数据乱码问题
查看>>
OVER(PARTITION BY)函数用法
查看>>
altium annotate 选项设置 complete existing packages
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>