How to get a method's annotation value from a ProceedingJoinPoint?

user755806 picture user755806 · Jan 22, 2014 · Viewed 64.2k times · Source

I have below annotation.

MyAnnotation.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

SomeAspect.java

public class SomeAspect{

 @Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")
    public Object procede(ProceedingJoinPoint call) throws Throwable {

  //Some logic

}

}

SomeOther.java

public class SomeOther{

@MyAnnotation("ABC") 
public String someMethod(String name){


}


}

In above class am passing "ABC" with in @MyAnnotation. Now how can i access "ABC" value in procede method of SomeAspect.java class?

Thanks!

Answer

René Link picture René Link · Jan 22, 2014

You can get the Signature from a ProceedingJoinPoint and in case of a method invocation just cast it to a MethodSignature.

@Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")
public Object procede(ProceedingJoinPoint call) throws Throwable {
    MethodSignature signature = (MethodSignature) call.getSignature();
    Method method = signature.getMethod();

    MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
}

But you should first add an annotation attribute. Your example code doesn't have one, e.g.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    String value();
}

Then you can access it

MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
String value = myAnnotation.value();

EDIT

How to get value if I have @MyAnnotation("ABC") at class level ?

A Class is also an AnnotatedElement, so you can get it the same way as from a Method. E.g. An annotation of the method's declaring class can be obtained using

 Method method = ...;
 Class<?> declaringClass = method.getDeclaringClass();
 MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class)

Since you are using spring you might also want to use spring's AnnotationUtils.findAnnotation(..). It searches for an annotation as spring does. E.g. also looking at superclass and interface methods, etc.

 MyAnnotation foundAnnotation = AnnotationUtils.findAnnotation(method, MyAnnotation.class);

EDIT

You might also be interessted in the capabilities of spring's MergedAnnotations which was introduced in 5.2.