annotationsaspectjpointcuts

Different resolution scope for Named and Anonymous pointcut annotations?


I am using AspectJ annotations and for some reason it seems that the resolution scope of pointcuts differs for a named pointcut versus an anonymous pointcut.

For example in the code below an identical pointcut is resolved if anonymous but not when it is named. The named pointcut will however match if I use a wildcard instead of a specific type.

Any thoughts?

import some_other_package.not_the_one_where_this_aspect_is.Account;

@Aspect
public class MyClass {


//this does not match... but matches if Account is replaced by *
@Pointcut("execution(* Account.withdraw(..)) && args(amount)")
public void withdr(double amount){}

@Before("withdr(amount)")
public void dosomething1(double amount){}


//this matches
@Before("execution(* Account.withdraw(..)) && args(amount)")
public void dosomthing2(double amount){}

}

Solution

  • In @AspectJ syntax imports are not useful according to the documentation. You need to either fully qualify class names or use jokers. That the import works in your second case, is rather an aberration from the expected behaviour than to be expected. You cannot rely on it.

    If you do it like this, both variants will work:

    @Aspect
    public class AccountInterceptor {
        @Pointcut("execution(* *..Account.withdraw(..)) && args(amount)")
        public void withdraw(double amount) {}
    
        @Before("withdraw(amount)")
        public void doSomething1(JoinPoint joinPoint, double amount) {
            System.out.println(joinPoint + " -> " + amount);
        }
    
        @Before("execution(* *..Account.withdraw(..)) && args(amount)")
        public void doSomething2(JoinPoint joinPoint, double amount) {
            System.out.println(joinPoint + " -> " + amount);
        }
    }