M02 Q06 How to enable the detection of the @Aspect annotation?
What do you have to do to enable the detection of the @Aspect annotation?
To enable detection of @Aspect annotation you need to perform the following steps
Step 1. Add spring-aspects dependency. Without required dependencies on classpath, spring will fail with ClassNotFoundException/NoClassDefFoundError during the creation of Proxy objects for Spring Beans subject to aspects
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency>
Step 2. Create @Configuration class and annotate it with @EnableAspectJAutoProxy annotation. Without @EnableAspectJAutoProxy Spring will not scan for @Aspect at all.
Step 3. Also, you need to have beans for @Aspect annotated classes. There are two ways to create those beans
- Use
@ComponentScanwith@Componentat class annotated with@Aspect
- Use
@Beanin Configuration class and create Spring Aspect Bean manually
What does @EnableAspectJAutoProxy do?
Annotation @EnableAspectJAutoProxy enables detection of @Aspect classes and creates a proxy object for beans subject to aspects. Internally process of creating proxies is done by AnnotationAwareAspectJAutoProxyCreator. By creating a proxy for each bean subject to aspects, Spring intercepts the calls and implements Before / After / AfterReturning / AfterThrowing / Around advices.
It is important to remember that @Aspect will not create Spring Beans on its own, you need to use Component Scanning or manually create beans for @Aspect classes.