Spring @Async method called from within the class

568 Views Asked by At

I've an spring component which has some methods as @Async.

I want to create a private method and run @Async but it won't works because spring doesn't help self invocation from withing the bean...

Is there a simple way to allow a specific private method to allos AOP @Async? or is just simpler to get a threadpool and execute manually?

1

There are 1 best solutions below

5
Yevgeniy On

instead of calling your async method on this, inject the bean and call the method on the bean. here is a example:

public class MyService {
    
    @Lazy
    @Autowired
    private MyService myService;
    
    public void doStuff() throws Exception {
        myService.doStuffAsync();
        System.out.println("doing stuff sync.");
    }
    
    @Async
    public void doStuffAsync() throws Exception {
        TimeUnit.SECONDS.sleep(3);
        System.out.println("doing stuff async.");
    }
}
  • you have to use @Lazy!
  • you have to call myService.doStuffAsync() instead of this.doStuffAsync()