如何在Spring方面访问自定义注释值 [英] how to access custom annotation values in spring aspect
问题描述
我正在尝试从jointCut访问自定义注释值.但是我找不到办法.
I am trying to access the custom annotation values from jointCut. But I couldn't find a way.
我的示例代码:
@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION)
public boolean validator(Map<String,String> mapStr) {
//blah blah
}
尝试访问 @Aspect
类.
但是,我没有看到任何访问值的范围.
But, i didnt see any scope to access values.
我尝试访问的方式在代码下方
Way i am trying to access is below code
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
String[] names = codeSignature.getParameterNames();
MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
Object[] values = joinPoint.getArgs();
我没有看到任何值返回input = input1.如何实现这一目标.
i didnt see any value returns input = input1. how to achieve this.
推荐答案
从纯Java的角度来看, Jama Asatillayev 的答案是正确的,但它涉及反思.
While the answer by Jama Asatillayev is correct from a plain Java perspective, it involves reflection.
但是问题特别是关于Spring AOP或AspectJ,并且有一种更简单,更规范的方法,可以使用AspectJ语法将匹配的注释绑定到方面建议参数,而无需任何反思,BTW.
But the question was specifically about Spring AOP or AspectJ, and there is a much simpler and more canonical way to bind matched annotations to aspect advice parameters with AspectJ syntax - without any reflection, BTW.
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import my.package.ComponentValidation;
@Aspect
public class MyAspect {
@Before("@annotation(validation)")
public void myAdvice(JoinPoint thisJoinPoint, ComponentValidation validation) {
System.out.println(thisJoinPoint + " -> " + validation);
}
}
这篇关于如何在Spring方面访问自定义注释值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!