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

结果输出如下:
这里写图片描述

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值