springboot註解實現非同步呼叫時no bean of type TaskExecutor and no bean named 'taskExecutor' either

bin929發表於2018-07-20

在使用springboot 註解@Async 實現非同步呼叫時。
啟動類:

@EnableAsync//啟動非同步
public class JtaAtomikosApp {

    public static void main(String[] args){
        SpringApplication.run(JtaAtomikosApp.class,args);
    }

}

controller類:

 @Autowired
    private TestYiBu testYiBu;

    @ResponseBody
    @RequestMapping("/sendMsg")
    public String sendMsg(){

        System.out.println("test 非同步 1");
        testYiBu.sendMsg();//非同步呼叫方法
        System.out.println("test 非同步 2");
        return "test";
    }

呼叫的非同步類

package com.boot.other;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component//注入到SpringBoot容器
public class TestYiBu {

    @Async//非同步載入標誌
    public String sendMsg(){
        System.out.println("test 非同步 3");
        for (int i=1; i<=3 ;i++){
            System.out.println("i=" + i);
        }
        System.out.println("test 非同步 4");
        return "success";
    }
}

結果輸出如下:
這裡寫圖片描述

如圖所示,雖然實現了非同步的呼叫,但是出現了異常:
No task executor bean found for async processing: no bean of type TaskExecutor and no bean named ‘taskExecutor’ either

解決方法:
修改啟動類如下:

@EnableAsync//啟動非同步
public class JtaAtomikosApp {

    public static void main(String[] args){
        SpringApplication.run(JtaAtomikosApp.class,args);
    }

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

結果如圖:
這裡寫圖片描述

其他方法:
解決方法參照:https://www.jb51.net/article/137259.htm

相關文章