@Async not working for me

前端 未结 4 955
情话喂你
情话喂你 2020-12-16 00:46

I am using @Scheduled and it have been working fine, but can\'t get the @Async working. I tested it many times, and seems that it is making my method asynchronous. Is there

相关标签:
4条回答
  • 2020-12-16 00:58

    I had a problem similar to this. And I spent a lot of time to fix it.

    If you use spring-context 3.2, you also need to add @EnableAsync on the class where you call the method service annotated @Async

    Take a look at http://spring.io/guides/gs/async-method/#initial

    I hope that it'll help you.

    0 讨论(0)
  • 2020-12-16 01:00

    You can use @EnableAsync in your service...

    0 讨论(0)
  • 2020-12-16 01:04

    As you're calling your @Async method from another method in the same object, you're probably bypassing the async proxy code and just calling your plain method, ie within the same thread.

    One way of solving this is by making sure your call to the @Async method is from another object. See comments at end of this article: http://groovyjavathoughts.blogspot.com/2010/01/asynchronous-code-with-spring-3-simple.html

    But it gets messy doing things like that, so you could just autowire the TaskScheduler, wrap up your method in a Runnable and execute it yourself.

    0 讨论(0)
  • 2020-12-16 01:09

    This is a complementary answer to the accepted one. You can call an async method in your own class, but you have to create a self-referential bean.

    The only side-effect here is that you cannot call any async code inside the constructor. It is a nice way to keep your code all in the same place.

    @Autowired ApplicationContext appContext;
    private MyAutowiredService self;
    
    @PostConstruct
    private void init() {
        self = appContext.getBean(MyAutowiredService.class);
    }
    
    public void doService() {
        //This will invoke the async proxy code
        self.doAsync();
    }
    
    @Async 
    public void doAsync() {
        //Async logic here...
    }
    
    0 讨论(0)
提交回复
热议问题