Reputation: 24561
I am new to Spring AOP.
Using annotation based Spring configuration:
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan({"sk.lkrnac"})
Aspect:
@Aspect
@Component
public class TestAspect {
@Before("execution(* *(..))")
public void logJoinPoint(JoinPoint joinPoint){
....
}
}
Spring compoment:
package sk.lkrnac.testaop;
@Component
public class TestComponent{
@PostConstruct
public void init(){
testMethod();
}
public void testMethod() {
return;
}
}
How can I intercept all public methods that are called by Spring framework itself? (e.g. TestComponent.init() during creation of the TestComponent instance by Spring)
Currently I am able to intercept only TestComponent.testMethod()
by invoking:
TestComponent testComponent = springContext.getBean(TestComponent.class);
testComponent.testMethod();
Upvotes: 4
Views: 3606
Reputation: 1
You can also try to call inner testMethod() from init() by self via proxy object like Don explained in https://stackoverflow.com/a/5786362/6786382.
Upvotes: 0
Reputation: 27614
This is a common issue you run into with Spring AOP. Spring accomplishes AOP by proxying advised classes. In your case, your TestComponent
instances will be wrapped in a run-time proxy class that provides the "hooks" for any aspect advice to be applied. This works very well when methods are called from outside the class, but as you have discovered it doesn't work on internal calls. The reason is that internal calls will not pass the proxy barrier, thus will not trigger the aspect.
There are primarily two ways around this. One is to fetch an instance of the (proxied) bean from the context. This is what you have already tried with success.
The other way is to use something called load-time weaving. When using this, AOP advices are added to a class ("weaved" into it) by a custom class-loader by injecting byte-code into the class definition. The Spring documentation has more on this.
There is a third way, which is called "compile time weaving". In this scenario, your AOP advices are statically weaved into each advised class when you compile it.
Upvotes: 6
Reputation: 493
You can't intercept init()
without any explicit means, please see the SpringSource Jira for details.
Upvotes: 1