由于业务需要,需要在自定义注解中将参数中的值传入到注解的指定属性中,这很容易让我联想到 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; ListparamNameList = Arrays.asList(methodSignature.getParameterNames()); List
这个地方,我是在方法执行完毕后的切面中进行操作, 可以根据业务需要自行决定在哪里使用. 代码中的 primaryKey.primaryKey()
分别是我所自定义的注解名和注解属性d