-1

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

jozinho22
  • 459
  • 2
  • 7
  • 24

1 Answers1

1

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

R.G
  • 6,436
  • 3
  • 19
  • 28
  • Thank you, if I did understand well, I have to call the method testAop from another class, and I can get rid of my EnableAspectJAutoProxy annotation which is useless because it's already managed by the SpringBootApplication annotation ? – jozinho22 Dec 04 '20 at 15:16
  • 1
    Not exactly 1. You can advice a Spring bean using Spring AOP , which means , the `testAop()` method should be in a bean ( which is not an aspect ) and the point cut designator should be targeting that method. 2. Yes , `@EnableAspectJAutoProxy` is redundant as it is managed by the `@SpringBootApplication` annotation. – R.G Dec 04 '20 at 15:20
  • Please update the question with your new code – R.G Dec 04 '20 at 15:42