Why Spring AOP is not working for method call inside another method?

僤鯓⒐⒋嵵緔 提交于 2019-12-12 01:12:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21625588/why-spring-aop-is-not-working-for-method-call-inside-another-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!