varun
varun

Reputation: 726

Annotation value in advice

I want to access my annotation values in advice, my annotation can be placed on type or method. so far i am able to get the annotation value when applied on method but no success when the annotation is applied on type.

@Before( value = "(@annotation(varun.mis.aspect.Logged) || within(@varun.mis.aspect.Logged *)) && (@annotation(logged))",argNames = "logged" )

Any suggestion?

Upvotes: 1

Views: 881

Answers (2)

Hearen
Hearen

Reputation: 7828

Have a try as follows using annotation directly: add com.mycompany.MyAnnotation yourAnnotation in your advice params and @annotation(yourAnnotation) in @Around.

@Around("execution(public * *(..)) && @annotation(yourAnnotation)")
public Object procede(ProceedingJoinPoint pjp, com.mycompany.MyAnnotation yourAnnotation) {
    ...
    yourAnnotation.value(); // get your annotation value directly;
    ...
}

com.mycompany.MyAnnotation in advice params just work as that in

@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")

yourAnnotation can be valid variable name since MyAnnotation in params already points out which annotation it should be. Here yourAnnotation is used to retrieve the annotation instance only.

If you want to pass more params you can try args().

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

I don't believe you can get the annotation as an argument when applied to a type

The following pointcut expression

@Before("@annotation(com.some.TestAnnotation) || within(@com.some.TestAnnotation *)")

will match either a method annotated or a class annotated. You can then declare the advice to get the annotation either from the method or from the class

MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
TestAnnotation annotation = methodSignature.getMethod().getAnnotation(TestAnnotation.class);
if (annotation == null) {
    Class<?> clazz = methodSignature.getDeclaringType();
    annotation = clazz.getAnnotation(TestAnnotation.class);
    if (annotation == null) {
        System.out.println("impossible");
    } else {
        System.out.println("class has it");
    }
} else {
    System.out.println("method has it");
}

You should also consider the case where both the method and the type have the annotation.

Upvotes: 3

Related Questions