简体   繁体   中英

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?

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

There is sort of a workaround. In your example, you can add an extra 'default' method eg named fooFacade to your FakeTemplate interface, annotate that with your @CustomAnnotation, and then delegate to the 'real' foo method:

public interface FakeTemplate {

    @CustomAnnotation
    default void fooFacade() {
        foo();
    }

    void foo();
}

Now whenever you call fooFacade(), execution of the pointcut on @CustomAnnotation will be triggered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM