Thursday, January 24, 2013

Aspectj pointcut expression based on annotation on types/methods

Consider two classes, one with annotation applied on the type and one with annotation on a method:

@CustomAnnotation
public class Class1 {
 
 public void method11(){}

 public void method12(){}
}

public class Class2 {
 
 @CustomAnnotation
 public void method21(){}
 
 public void method22(){}

}


I had to write a Aspectj pointcut which selects the methods on classes where the CustomAnnotation is applied on types - methods of Class1 above. My first gut feel was to write an aspect along these lines:
@Pointcut("execution(@CustomAnnotation  * *.*(..))")
public void methodsInAnnotatedTypes(){}

This pointcut is wrong though, as it ends up selecting methods of Class2.

The reason is this, the pointcut expression signature for execution pointcut type is the following(this is from the Spring documentation site available here):

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?.name-pattern(param-pattern) throws-pattern?)

To select the methods based on annotation on the type, I have to add the annotation to the declaring-type-pattern above like the following:

execution(modifiers-pattern? ret-type-pattern (@CustomAnnotation declaring-type-pattern?).name-pattern(param-pattern) throws-pattern?)

Having it in the beginning will select any methods with Custom annotation on the method:
execution(@CustomAnnotation modifiers-pattern? ret-type-pattern declaring-type-pattern?.name-pattern(param-pattern) throws-pattern?)

So with this fix the correct pointcut expression becomes, and this selects the methods of Class1:

@Pointcut("execution(* (@CustomAnnotation *).*(..))")
public void methodsInAnnotatedTypes(){
 
}


No comments:

Post a Comment