springboot注解实现异步调用时no bean of type TaskExecutor and no bean named 'taskExecutor' either

在使用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";
    }
}

结果输出如下:
springboot注解实现异步调用时no bean of type TaskExecutor and no bean named 'taskExecutor' either_第1张图片

如图所示,虽然实现了异步的调用,但是出现了异常:
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();
    }
}

结果如图:
springboot注解实现异步调用时no bean of type TaskExecutor and no bean named 'taskExecutor' either_第2张图片

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

你可能感兴趣的:(springboot)