Asynchronous execution aspect using AspectJ

Here is the problem -

I used @Async provided by Spring to execute some methods asynchronously. However, since it is based on a proxy server, it will not work if the method is called from the same class. I need my asynchronous methods to call from one class.

I know that if I use AspectJ instead of Spring AOP, I can do it.

So my question is, is there a way to use Spring @Async and load time to weave it? Or is there an asynchronous execution aspect already written by AspectJ that I can use instead of writing my own?

+4
source share
2 answers

Yes, annotate the method of the specific class with @Async , put the spring-aspects JAR (which contains the asynchronous aspect) in your classpath, use <task:annotation-driven mode="aspectj" /> in the Spring configuration and apply either compile time, or the -time weaving load, referring to spring-aspects as an aspect library.

+5
source

One thing you can do is to throw a bean together, whose sole purpose is to run things asynchronously and pass work to it inside the method. This may not make the API as pretty if you want to host @Async on your interfaces or something else, but it does the job.

 public interface AsyncExecutor { void runAsynchronously(Runnable r); } public class SpringAOPAsyncExecutor implements AsyncExecutor { @Async @Override public void runAsynchronously(Runnable r) { r.run(); } } public MyService implements SomeInterface { @Autowired private AsyncExecutor springAOPAsyncExecutor; public ObjectHolder calculateAsychronously() { final ObjectHolder resultHolder = new ObjectHolder(); springAOPAsyncExecutor.runAsynchronously ( new Runnable() { public void run() { //do some calculatin resultHolder.setValue(whatevs); } }); return resultHolder; } } 
+2
source

Source: https://habr.com/ru/post/1488765/


All Articles