0

I want to within my own Bean call a method within itself which has its own @Async and @Transactional proxies but it isnt working.

 public class MyClass {

private MyClass _selfWithProxy;

@PostConstruct
public void postContruct() {
    _selfWithProxy = applicationContext.getBean(MyClass.class);
}

void myMethodA() {
_selfWithProxy.myMethodB()
}

@Async
@Transactinal
void myMethodB() {
//do stuff
  }

However when I call myMethodA from another Bean the call to myMethodB does not intercept with an Async interceptor. I can see _selfWithProxy is a proxy bean, and the proxy activates but there are is no Async interceptor in the chain.

When I call myMethodB from another bean the @Async works, so I know it is setup correctly

1 Answers1

0

Self invocation won't work for @Async. I believe that is because the proxy (your code + AOP advice) object calls your methodA on the target object (just your code) which then calls it's own methodB which isn't advised by AOP. In general I would not advise having spring bean methods call other methods of the same bean.

"@Async has two limitations:

It must be applied to public methods only. Self-invocation — calling the async method from within the same class — won't work. The reasons are simple: The method needs to be public so that it can be proxied. And self-invocation doesn't work because it bypasses the proxy and calls the underlying method directly."

https://www.baeldung.com/spring-async

  • Technically this is not self invocation in the same way that article describes. – user2323975 Mar 02 '22 at 09:45
  • By injecting self into itself, I am activating the proxy, I have confirmed this by debugging – user2323975 Mar 02 '22 at 09:46
  • An answer here has what I am trying to do https://stackoverflow.com/questions/3423972/spring-transaction-method-call-by-the-method-within-the-same-class-does-not-wo – user2323975 Mar 02 '22 at 09:47