Evgeniy has a solution, I just want to explain what happens.
When you specify
<aop:aspectj-autoproxy />
or annotate a @Configuration
class (which you load) with @EnableAspectJAutoProxy
, Spring registers a AnnotationAwareAspectJAutoProxyCreator
which is a BeanPostProcessor
that
processes all AspectJ annotation aspects in the current application
context, as well as Spring Advisors. Any AspectJ annotated classes
will automatically be recognized, and their advice applied if Spring
AOP's proxy-based model is capable of applying it.
One step of this process includes finding candidate Advisors. It does so by scanning your bean definitions and checking the bean types. This happens before any beans have been created and therefore the process can only rely on what has been declared. It's guessing.
With <bean>
declarations, it wouldn't usually be a problem because you would specifically declare the bean's class in the class
attribute.
With @Bean
methods however, you can specify an interface instead. Note that <bean>
and @Bean
declarations could both fail if you were using a factory method to generate the bean.
So the AnnotationAwareAspectJAutoProxyCreator
looks at all the bean definitions in the context and guesses their type. With a @Bean
declaration, it looks at the method's return type.
In your case, the return type will be MindReader
which is not a candidate since it does not have an @Aspect
annotation. As such, no advice (no proxies) will be applied and you won't see the behavior you were expecting.
Possible solutions:
- Evgeniy's solution to change the return type and therefore make it obvious to Spring what the bean type is
- Get rid of your
@Bean
definition, annotate your Magician
class with @Component
, and have its package be component-scan
ned. Because the type is obviously the annotated class, Spring will be able to tell that it's also annotated with @Aspect
.
Note that are many other BeanPostProcessor
implementations that guess the type of the bean. You have to be aware at which point (before or after initialization) processing happens.