Search code examples
javaspringaopaspectjinterceptor

Spring Aspectj Around advice does not work with interface implementations


I have one interface and its implementations.

interface A{
    String methodA();
    String methodB();
}

public class Impl1 implements A{

    @Override
    public String methodA() {
        methodB();
        return "";
    }

    @Override
    public String methodB() {
        return "";
    }
}

public class Impl2 implements A{

    @Override
    public String methodA() {
        methodB();
        return "";
    }

    @Override
    public String methodB() {
        return null;
    }
}

What i want to intercept when any of the implementations of A interface && execution of methodB().

@Around("within(com.bla.bla.A+) && execution(* methodB(..))")

But this did not work. When i remove execution part, it works but for calling method of the outside. Any idea would be appreciated.

Note: methodb is not triggered direcly out of the interface. it triggers in interface implementations.


Solution

  • Spring AOP works on proxies. Calling methodB() from methodA() is called a self-invocation. Spring AOP will not be able to advice the method call to methodB() from methodA() , as it will not go through the proxy.

    Spring reference documentation : Understanding AOP Proxies . Read through the section starting with The key thing to understand here is that the client code inside the main(..)