@Async not working for me

前端 未结 4 963
情话喂你
情话喂你 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 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...
    }
    

提交回复
热议问题