spring-bootaspectjspring-aopaspectspring-aspects

Why my @Aspect is not recognized by my SpringBoot Application?


I want to test the AOP with spring boot, hence I imported this dependency in my

pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

Then i created two classes, one for configuration and an other responsible for weaving aspect.

AspectConfig.class

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.douineau.aspect")
public class AspectConfig {

}

And the other class, which does nothing special except testing if it's working well :

ControllerAspect.class

@Aspect
@Component
public class ControllerAspect {
    
    @Pointcut("execution(* com.douineau.aspect.ControllerAspect.testAop(..))")
    public void callingRequest() {
        System.out.println("Pointcut method done");
    }
    
    @Before("callingRequest()")
    public void beforeAdvice( ) {
        System.out.println("Before advice");
    }

    public void testAop() {
        System.out.println(getClass().getName());
    }

}

When i'm calling the method c.testAop(), it is supposed to enter in the method callingRequest() with the parameterized @Pointcut("execution(* com.douineau.aspect.ControllerAspect.testAop(..))") annotation.

But it don't...

An other thing to really understand, does it would be more pertinent to place the @EnableAspectJAutoProxy annotation directly after the @SpringBootApplication of the main SpringBoot launcher ?

Thank you for your help.

Joss


Solution

  • From Spring framework reference documentation:

    Advising aspects with other aspects? In Spring AOP, aspects themselves cannot be the targets of advice from other aspects. The @Aspect annotation on a class marks it as an aspect and, hence, excludes it from auto-proxying.

    Here the pointcut expression is targeting an Aspect , which is not possible in Spring AOP.

    For a Spring Boot application , one need not explicitly declare @EnableAspectJAutoProxy. Please read through this question and answer

    As long as the recommeded structuring is followed , your aspects should be picked without explicitly specifying a @ComponentScan