2

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() {
       ...      
    }
}
user1491636
  • 2,355
  • 11
  • 44
  • 71
  • Did you enable the Spring Auto proxy? How did you create an instance of the `TestClass`? – Ali Dehghani May 25 '16 at 23:23
  • `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 `` in the application context. Anything else required? – user1491636 May 26 '16 at 13:34

1 Answers1

0

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();
   }
}
Bond - Java Bond
  • 3,972
  • 6
  • 36
  • 59
  • In my example, `TestClass` is a spring managed bean. It's defined my the application context. Is that not sufficient enough? – user1491636 May 30 '16 at 18:36
  • No, as I mentioned in my answer for `TestClass.test()` to be intercepted it should be invoked via _another bean_. The plain invocation within same bean does not kicks in the registered aspects. – Bond - Java Bond May 31 '16 at 06:29
  • Java Bond, Is there another option? The `TestClass` cannot be autowired. I can however make it a bean (defined in the app context) which gets set through the constructor of `AnotherTestClass` (another bean defined in app context). Is there a way to get it to work with that given setup? Thanks! – user1491636 May 31 '16 at 13:29
  • If both the beans are defined in same context then you can very well autowire them. Any specific reason why you think it can't be? – Bond - Java Bond May 31 '16 at 13:43
  • Without going into much detail, its just the nature of the beans and app. – user1491636 May 31 '16 at 14:34
  • Without sounding rude, frankly its weird that beans defined in same context can not be autowired. With the little information made available unfortunately there is not much options can be explored. – Bond - Java Bond May 31 '16 at 16:52