Senior
What will happen if you call an @Async method from a non-annotated method within the same bean?
sobes.tech AI
Answer from AI
If you call a method annotated with @Async from another method within the same bean that is not annotated, the asynchrony will not work.
The reason is that Spring uses proxies to implement @Async. When calling a method within the same class, the call is direct, bypassing the proxy, and the annotation is ignored.
As a result, the method will execute synchronously in the same thread.
For @Async to work, the call must come from outside through a proxy, for example, from another bean or via the ApplicationContext.
Example:
@Component
public class MyService {
@Async
public void asyncMethod() {
// executes asynchronously
}
public void syncMethod() {
asyncMethod(); // call within the class — will be synchronous
}
}
To fix this, you can:
- Move
asyncMethodto another bean and call it from there. - Use
ApplicationContextto get the proxy and call the method through it. - Or use
@EnableAsync(proxyTargetClass=true)and CGLIB proxies, but calls within the class still won't be proxied.