Spring AOP not working for method call inside anot

2019-01-04 09:56发布

There are two methods defined in ABC.java

public void method1(){
   .........
   method2();
  ...........
}


public void method2(){
  ...............
  ...............  
}

I want to have AOP on call of method2.So, I created one class,AOPLogger.java,having aspect functionality provided in a method checkAccess
In configuration file, I did something like below

<bean id="advice" class="p.AOPLogger" />
<aop:config>
  <aop:pointcut id="abc" expression="execution(*p.ABC.method2(..))" />
  <aop:aspect id="service" ref="advice">
    <aop:before pointcut-ref="abc" method="checkAccess" />          
  </aop:aspect>
</aop:config>

But when my method2 is called, AOP functionality is not getting invoked i.e. checkAccess method is not getting invoked of AOPLogger class.

Any thing i am missing?

9条回答
欢心
2楼-- · 2019-01-04 10:30

Annotate calls with @EnableAspectJAutoProxy(exposeProxy = true) and call the instance methods with ((Class) AopContext.currentProxy()).method();

This is strictly not recommended as it increases to coupling

查看更多
何必那么认真
3楼-- · 2019-01-04 10:35

It is not possible what you want to achieve. An explanation is in the Spring Reference Documentation.

查看更多
可以哭但决不认输i
4楼-- · 2019-01-04 10:38

Spring AOP framework is "proxy" based and it is explained very well here: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies

When Spring constructs a bean that is configured with an aspect (like "ABC" in your example), it actually creates a "proxy" object that acts like the real bean. The proxy simply delegates the calls to the "real" object but by creating this indirection, the proxy gets a chance to implement the "advice". For example, your advice can log a message for each method call. In this scheme, if the method in the real object ("method1") calls other methods in the same object (say, method2), those calls happen without proxy in the picture so there is no chance for it to implement any advice.

In your example, when method1() is called, the proxy will get a chance to do what ever it is supposed to do but if method1() calls method2(), there is no aspect in the picture. How ever, if method2 is called from some other bean, proxy will be able to carry out the advice.

Hope this helps.

Thanks, Raghu

查看更多
登录 后发表回答