Search code examples
javaspringaopaspectjspring-aop

AspectJ Pointcut doesn't work on Annotations with Element.TYPE like @Component


I'm using AspectJ and I trying to Pointcut on @Component annotation.

@Pointcut("@annotation(org.springframework.stereotype.Component)")
   public void bean() {
}

@Before("bean()")
public void beforeBeanCreation(JoinPoint jp) {
    System.out.println("Works!");
}

My configuration looks like below:

@Configuration
@ComponentScan({"com.app.pl"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
public class AppConfiguration{

}

Everything works when I want to pointcut on annotation with ElementType.METHOD, or on a bean with specific name. But Pointcut on annotation with ElementType.TYPE dosen't work. I speculate that is a problem related with annotations that they are readed earlier then AspectJ proxy stand up.

Any idea how to solve this?


Solution

  • Probably you are not using AspectJ but Spring AOP. So there are a few things to consider:

    • Usually Spring AOP aspects work on @Components anyway, not on non-Spring stuff. For that you would really need AspectJ. So in a way your Spring AOP aspects look for that annotation anyway.
    • Spring AOP aspects should be @Components too, but are excluded from aspect weaving automatically. In AspectJ you would need special precautions to exclude one aspect weaving another one bearing the same annotation as normal application code. You would need to consider that in situations where you combine Spring AOP with full AspectJ.

    Now as for your AOP question, you cannot intercept joinpoints in an annotated class via @annotation() pointcut, as you already noticed. You need to use @within() instead, e.g.:

    @within(org.springframework.stereotype.Component)
    

    Please note that this will intercept all joinpoints in annotated classes, i.e. in the case of Spring AOP all method executions. It will not intercept bean creation, if as your log message suggests that is your goal.