Reputation: 1175
Why Spring AOP is not working for method call inside another method?
public class TestAOPService {
public String getSum(int val1) {
System.out.println(val1);
calculateSum(val1, 12);
}
public void calculateSum(int val1, int val2){
System.out.println("Sum" + (val1 + val2));
}
}
can anyone explain how to achieve this?
Upvotes: 1
Views: 1615
Reputation: 280172
Because of how proxying works.
For example, Spring creates a bean, an instance of type TestAOPService
. Then it realizes it needs to proxy it to add aspect advice. It will take the class (and interface) type of the instance and create either a JDK proxy or a CGLIB proxy.
The proxy will wrap the actual instance and delegate to it after/around/before executing the advice.
It looks like this
Caller --> Proxy.getSum(..) --> Bean.getSum(..)
So the caller is invoking the method on the proxy and the proxy contains the advice behavior. But, if you call a method of the instance within a method of the instance, it looks like so
Caller --> Proxy.getSum(..) --> Bean.getSum(..) --> Bean.calculateSum(..)
In code, you'd have this
public String getSum(int val1) {
System.out.println(val1);
calculateSum(val1, 12);
}
which is actually
public String getSum(int val1) {
System.out.println(val1);
this.calculateSum(val1, 12);
}
The method is invoked directly on the instance, not on the proxy. Therefore no advice can be applied.
Upvotes: 3