Spring AOP not working for method call inside another method

JavaSpringSpring Aop

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

Update 2022:

Now I personally prefer using TransactionHandler class described here - much cleaner and flexible way.

Original answer:

It can be done by self injection usage. You can call inner method through injected instance:

@Component
public class Foo {
    @Resource
    private Foo foo;
    
    public void method1(){
        ..
        foo.method2();
        ..
    }
    public void method2(){
        ..
    }
}

Since Spring 4.3 you also can do it using @Autowired.

> As of 4.3, @Autowired also considers self references for injection, > i.e. references back to the bean that is currently injected.

Solution 3 - Java

Spring AOP framework is "proxy" based, the documentation at Understanding AOP Proxies explains it very well.

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. However, if method2 is called from some other bean, the proxy will be able to carry out the advice.

Solution 4 - Java

I had the same kind of problem and I overcame by implementing Spring's ApplicationContextAware,BeanNameAware and implementing corresponding methods as below.

class ABC implements ApplicationContextAware,BeanNameAware{

      @Override
      public void setApplicationContext(ApplicationContext ac) throws BeansException {
          applicationContext=ac;
      }
  
      @Override
      public void setBeanName(String beanName) {
          this.beanName=beanName;
      }
      private ApplicationContext applicationContext;
      private String beanName;
}

then I replaced this. with ((ABC) applicationContext.getBean(beanName)). while calling the methods of the same class. This ensures that calls to methods of the same class happen through the proxy only.

So method1() changes to

 public void method1(){
    .........
    ((ABC) applicationContext.getBean(beanName)).method2();
    ...........
  }

Hope this helps.

Solution 5 - Java

Using @Autowired it works. Instead of calling the inner method as this.method(), you can do:

@Autowired
Foo foo;

and then calling:

foo.method2();

Solution 6 - Java

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

Solution 7 - Java

As indicated in the Spring docs, chapter 5.6.1 Understanding AOP proxies, there is another way you can do:

public class SimplePojo implements Pojo {

    public void foo() {
        // this works, but... gah!
        ((Pojo) AopContext.currentProxy()).bar();
    }

    public void bar() {
        // some logic...
    }
}

Although the author doesn't recommand this way. Because:

> This totally couples your code to Spring AOP, and it makes the class itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. It also requires some additional configuration when the proxy is being created.

Solution 8 - Java

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

Solution 9 - Java

I am surprised no one mentioned this but i think we can use ControlFlowPointcut provided by Spring.

ControlFlowPointcut looks at stacktrace and matches the pointcut only if it finds a particular method in the stacktrace. essentially pointcut is matched only when a method is called in a particular context.

In this case, we can create a pointcut like

ControlFlowPointcut cf = new ControlFlowPointcut(MyClass.class, "method1");

now, using ProxyFactory create a proxy on MyClass instance and call method1().

In above case, only method2() will be advised since it is called from method1().

Solution 10 - Java

Another way around is to mode the method2() to some other Class File ,and that class is annotated with @Component. Then inject that using @Autowired when you need that.This way AOP can intercept that.

Example:

You were doing this...


Class demo{
   method1(){
   	-------
   	-------
    method2();
    -------
    -------
   }

   method2(){
   	------
   	-----
   }
}

Now if possible do this :

@Component
class NewClass{
	method2(){
   	------
   	-----
   }
}


Class demo{

 @AutoWired
 NewClass newClass;

   method1(){
   	-------
   	-------
    newClass.method2();
    -------
    -------
   }

}

Solution 11 - Java

You can refer to this question: https://stackoverflow.com/a/30611671/7278126

It's a workaround but will do the trick, the key here is to use the same bean (proxy) to invoke 'method2' instead of this.

Solution 12 - Java

After a lot of research, I found the following which works like a charm. But there is always a better way with ASPECTJ WEAVING. In essence of time use a self reference.

@Autowired
private ApplicationContext applicationContext;
private <<BEAN>> self;

> Please note the <> is of the same class which needs to be logged with AOP or to be used for something else.

@PostConstruct
private void init() {
    self = applicationContext.getBean(MyBean.class);
}

> With this change all you have to do is move the calls for > > this.methodName(args) -> self.methodName(args)

Hope this helps all who want to use a solution for just performance logging in the application.

Solution 13 - Java

You could do this :

@Autowired // to make this bean refers to proxy class 

ABC self;

public void method1(){

   .........

   self.method2();

  ...........

}


public void method2(){

  ...............

  ...............  

}

Solution 14 - Java

You can do self-injection this way so that this class can be used outside Spring application.

@Component
public class ABC {
	
	@Resource
	private ABC self = this;

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

	public void method2() {
		
	}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnandView Question on Stackoverflow
Solution 1 - JavaBrian AgnewView Answer on Stackoverflow
Solution 2 - JavaKonstantin ZyubinView Answer on Stackoverflow
Solution 3 - JavaRaghuramView Answer on Stackoverflow
Solution 4 - JavapavanView Answer on Stackoverflow
Solution 5 - JavaRashmingadhviView Answer on Stackoverflow
Solution 6 - JavaUwe PlonusView Answer on Stackoverflow
Solution 7 - JavaQianyueView Answer on Stackoverflow
Solution 8 - Javashiva kumarView Answer on Stackoverflow
Solution 9 - JavaArjun PatilView Answer on Stackoverflow
Solution 10 - JavaAbhishek SenguptaView Answer on Stackoverflow
Solution 11 - JavaAHM200View Answer on Stackoverflow
Solution 12 - JavaDoogleView Answer on Stackoverflow
Solution 13 - JavaAli ShomanView Answer on Stackoverflow
Solution 14 - JavaFaiView Answer on Stackoverflow