javaspringinterfaceannotationsspring-aop

Spring aspect call on custom annotation on interface method


I have this interface:

public interface FakeTemplate {

    @CustomAnnotation
    void foo() {

    }

}

And this implementation of the interface:

@Component
public FakeImpl implements FakeTemplate {

    @Override
    public void foo() {
        //Do Stuff
    }

}

And this aspect:

@Aspect
@Component
public class CustomAspect {

    @Before(value = "@annotation(com.fake.CustomAnnotation)")
    public void doStuffBefore(JoinPoint joinPoint} {

    }

}

I'm using spring with AspectJ enabled using: @EnableAspectJAutoProxy(proxyTargetClass = true)

My issue is that the aspect doStuffBefore method is not being called before the execution of FakeImpl's foo() method. It Does work when I put the @CustomAnnotation on FakeImpl instead of FakeTemplate, but I'd much prefer to put the annotation on FakeTemplate as it's in a separate API package and I've kind of delegated it as the place where I put all my annotations.

I'd also like to ensure that the CustomAnnotation is called on every class that implements FakeTemplate without remembering to put the annotation on all the implementation classes themselves.

Is there any way to get the advice to be called if the annotation is only on the interface class?


Solution

  • Annotation inheritance doesn't work for methods in java. But you can use other pointcut expression, something like execution(public * FakeTemplate+.foo(..))