1

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?

Rafael Lima
  • 3,079
  • 3
  • 41
  • 105

1 Answers1

2

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()
Yevgeniy
  • 2,614
  • 1
  • 19
  • 26
  • 1
    it will work i assume but this looks so ugly – Rafael Lima Jul 16 '22 at 20:32
  • i agree, but you need to provide more information about your problem. – Yevgeniy Jul 16 '22 at 21:01
  • 1
    Do note that this answer does not cover the main requirement of the question - `allow a specific private method`. Spring AOP cannot advise private methods . – R.G Jul 17 '22 at 03:34
  • as i understand OP wants to call a async public method from a private method, which will work fine. – Yevgeniy Jul 17 '22 at 07:07
  • Rafael, if you find it so ugly, switch to native AspectJ. No more proxies, easy to intercept self-invocation. You cannot have the full power of AspectJ in Spring's own "AOP lite" framework and have to make a choice. But AspectJ also works fine in Spring, just in a somewhat different way with regard to configuration and handling. – kriegaex Jul 20 '22 at 16:10