Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP not working for method call inside another method

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?

like image 603
Anand Avatar asked Nov 26 '12 12:11

Anand


People also ask

How AOP works internally in spring?

Spring AOP is proxy-based. Spring uses either JDK proxies (preferred wheneven the proxied target implements at least one interface) or CGLIB proxies (if the target object does not implement any interfaces) to create the proxy for a given target bean.

Which advice is invoked every single time in method calls?

Run advice after the method execution, regardless of its outcome. Run advice after the method execution, only if the method completes successfully. Run advice after the method execution, only if the method exits by throwing an exception. Run advice before and after the advised method is invoked.

Does AOP work on static methods?

Yes we can. Because we are accessing the class level members.


1 Answers

The aspect is applied to a proxy surrounding the bean. Note that everytime you get a reference to a bean, it's not actually the class referenced in your config, but a synthetic class implementing the relevant interfaces, delegating to the actual class and adding functionality, such as your AOP.

In your above example you're calling directly on the class, whereas if that class instance is injected into another as a Spring bean, it's injected as its proxy, and hence method calls will be invoked on the proxy (and the aspects will be triggered)

If you want to achieve the above, you could split method1/method2 into separate beans, or use a non-spring-orientated AOP framework.

The Spring doc (section "Understanding AOP Proxies") details this, and a couple of workarounds (including my first suggestion above)

like image 54
Brian Agnew Avatar answered Sep 18 '22 18:09

Brian Agnew