Search code examples
springaspectjspring-aopspring-aspects

how to access custom annotation values in spring aspect


I am trying to access the custom annotation values from jointCut. But I couldn't find a way.

My sample code :

@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION)
public boolean validator(Map<String,String> mapStr) {
    //blah blah
}

Trying to access @Aspect class.

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();

i didnt see any value returns input = input1. how to achieve this.


Solution

  • While the answer by Jama Asatillayev is correct from a plain Java perspective, it involves reflection.

    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);
        }
    }