SpringBoot 使用@autowired 注解,报错的解决方法,

故事背景:

   坑是这样的,写了一个class A对象,想在其类里面直接使用,为了方便就使用了@autowired注解,结果一直报异常,信息如下:

2022-08-31 19:29:27.496 ERROR 6972 --- [           main] o.s.test.context.TestContextManager      : 
Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@52af26ee] to prepare test instance [com.icoding123.wxpaydemo.HelloTest@325bb9a6]


org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.icoding123.wxpaydemo.HelloTest': Unsatisfied dependency expressed through field 'hm'; 

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.icoding123.wxpaydemo.HelloMan2' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

解决方案

经过N久的排查,才发现真正的原因,在class A里面不能有@Test注解,删除掉就好了

package com.icoding123.wxpaydemo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class HelloMan2 {
    @Value("${pay.wechat.appId}")
    private String appid;

    public String getAppid(){
        return "HelloMan2's "+appid;
    }

    //@Test  把这里注释掉 就可以被其他类 autowired 啦
    public void testme(){
        System.out.println("appid ="+appid);
    }
}

 写在最后

        编程的路上,坑很多,遇到问题解决问题。

今天总结了一下,大概思路是这样的,一般代码都是cv来的,然后修改一下,发现问题之后

  1. 和原来的代码进行对比,看是不是自己敲错代码啦
  2. 如果有官方文档可以去参考,可以先对比一下官方文档
  3. 看看是不是程序运行的环境是不是有不一样,比如第三方依赖版本,jdk版本等等
  4. 面向 baidu 和 google编程 ,懂的都懂,把错误信息帖上去搜索,一般我们想做的功能,前人都写过的,或者有类似的,多多参考对比

暂时就这么多了,欢迎大家多多讨论,文字来自一个84年的老哥

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值