Asynchronous execution aspect using AspectJ

泄露秘密 提交于 2019-12-22 05:35:09

问题


Here is the problem -

I was using @Async provided by Spring to execute some methods asynchronously. However, because it is proxy based, it wouldn't work if the method is called from within the same class. I do need my async methods to be called from within the same class.

I know if I use AspectJ instead of Spring AOP, I will be able to do that.

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


回答1:


Yes, annotate a concrete class' method with @Async, put spring-aspects JAR (which contains the async aspect) into your classpath, use <task:annotation-driven mode="aspectj" /> in your Spring config and apply either compile-time or load-time weaving, referencing spring-aspects as an aspect library.




回答2:


One thing you can do is toss together a bean whose only purpose is to run things asynchronously and pass the work to it inside the method. This may not make the API as pretty if you like to put @Async on your interfaces or whatever, but it gets the job done.

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;
  }
}


来源:https://stackoverflow.com/questions/17373307/asynchronous-execution-aspect-using-aspectj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!