2
votes

I'm trying to implement a simple Spring AOP (v4) example using @Before advice with an in-place pointcut expression, but the aspect method is not invoked. I have all the required dependencies(spring-aop, aopalliance, aspectweaver). What am I doing wrong?

package com.xyz;

public class TestClass {
    @PostConstruct
    public void init() {
        test();
    }
    public void test() {
       ...
    }
}

The aspect:

@Aspect
@Component
public class MyAspect{
    @Before("execution(* com.xyz.TestClass.test())")
    public void beforeTest() {
       ...      
    }
}
1
Did you enable the Spring Auto proxy? How did you create an instance of the TestClass? - Ali Dehghani
TestClass is a bean defined in my application context. It runs through the lifecycle when the application starts but the pointcut is never hit. I also have <aop:aspectj-autoproxy /> in the application context. Anything else required? - user1491636

1 Answers

0
votes

The reason why AOP isn't executed is because the TestClass.test() is not invoked in spring context but has simple / plain invocation from TestClass.init().

To test your setup modify it to something similar to below so that the TestClass.test() invocation is managed by spring

package com.xyz;

public class TestClass {

   public void test() {
     ...
   }
}

Inject the TestClass into another class say AnotherTestClass and invoke test method from there

package com.xyz;

public class AnotherTestClass {

   @Autowired
   private TestClass testClass;

   public void anotherTest() {
     testClass.test();
   }
}