Search code examples
javaaopaspectjspring-aoppointcut

Intercepting aspect for custom annotion


I am writing a library/sdk which can intercept any methods which are annotated with a custom annotation @Monitor. The code works somewhat like this

@Monitor
public void methodA(String test)

And the aspect which intercepts this has this pointcut expression

@After("execution(@com.packageA.Monitor * *(..))")
public void intercept(final JoinPoint joinPoint){
...}

This code works fine when I describe the aspect in the same package as the methodA. However if I create a separate library and define the aspect in that its not able to intercept the methodA . Any help?

EDIT

In response to @Bond's comment

@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {

}

Spring versions: spring-context - 4.1.7.Release aspectj - 1.6.5 The crux of the problem is that the annotation wont be used in the same project. After compilation it will be used in a different project all together.

EDIT2

The 2nd project i.e the one from which this aspect should be intercepting is compiled using aspectj maven plugin


Solution

  • You need to update the pointcut to @annotation(com.x.y.z.Monitor). (correct the package name accordingly)

    Thus your aspect should look something like below

    @After("@annotation(com.x.y.z.Monitor)") 
    public void intercept(final JoinPoint joinPoint){
        ...
    }
    

    Have a look at examples for reference about various pointcut expressions available. Also read this in case advise accepts argument(s)