spring Boot异步操作报错误: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying b...

本文探讨了在SpringBoot中使用@Async注解进行异步操作的常见问题及解决方法。详细介绍了Jeep类实现Runnable接口并使用@Async注解进行异步调用的过程,指出在异步操作中正确调用context.getBean(Runnable.class).run()的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我也是最近开始学习Spring Boot,在执行异步操作的时候总是汇报如下的错误:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.self.spring.springboot.Jeep' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1090) at com.self.spring.springboot.App.main(App.java:24)

 我运行的代码如下:

Jeep类:
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class Jeep implements Runnable {
    
  //异步注解 @Async
public void run() { try { for(int i=1;i<=10;i++){ System.out.println("==============" + i); TimeUnit.SECONDS.sleep(1); } } catch (Exception e) { e.printStackTrace(); } } }

main类:

@EnableAutoConfiguration
//使@Async注解生效 @EnableAsync @ComponentScan
public class App { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); System.out.println(context.getBean(TomcatProperties.class)); context.getBean(Jeep.class).run(); System.out.println("===========end==========="); context.close(); } }

错误分析:错误提示没有这个 com.self.spring.springboot.Jeep' available,但是已经存在这个类,后来查询了一会,非异步操作的时候,我们通过context.getBean(类名.class)来调用这个类里面的方法,但是在异步操作的时候,调用Jeep类实现了接口Runnable的方法,我们调用context.getBean(Runnable.class).run(),才会正常运行不报错。。

其实我也不得解答,如果有哪位高手看到了,请给我留言,已解我心中之谜。。。。

转载于:https://www.cnblogs.com/javJoker/p/7281688.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值