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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中,我们可以使用@Async注解实现异步方法调用。首先,我们需要在主类上添加@EnableAsync注解,以开启异步功能。然后,在需要异步执行的方法上添加@Async注解。Spring会将这些方法的执行放在异步线程中进行。使用@Async注解需要满足以下条件: 在测试类中,我们可以通过创建一个TaskExecutor来执行异步任务。首先,我们需要在测试类中注入TaskExecutor的实例。然后,我们可以使用taskExecutor.execute方法来执行异步任务。例如,在测试类中的test1方法中,我们使用taskExecutor.execute(() -> System.out.println("异步任务"));来执行一个异步任务。同,我们还可以使用同步操作来进行对比。执行完成后,我们可以通过StopWatch来计算耗,并输出结果。 因此,通过添加@Async注解和使用TaskExecutor来执行异步任务,我们可以在Spring Boot中实现异步调用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot实现异步调用的几种方式](https://blog.csdn.net/qinxun2008081/article/details/131093083)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值