No qualifying bean of type bean but found

1、报错分析

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xxx.trade.GrouponService' available: expected single matching bean but found 2: tradeGrouponService,@Reference com.xxx.trade.GrouponService

报错日志的表面意思:

希望指定一个明确的bean进行导入,但现容器中有2个bean ,分别是tradeGrouponService 和 @Reference com.xxx.trade.GrouponService

重点: 意思就是@Autowire 的时候,Spring 需要将 beanId= grouponService 的bean 注入到变量中,但容器里没有对应的bean对象。

接着,看下调用的位置:

    @Autowired
    private GrouponService grouponService;  

2、探索原因

继续查看项目里在哪里配置了bean的注入,最后发现了两处:

// 会向容器中导入beanId = @Reference com.xxx.trade.GrouponService 的bean 
    @Reference
    private GrouponService tradeGrouponService;

//会向容器中导入beanId=tradeGrouponService 的bean 
   @Bean
    public GrouponService tradeGrouponService() {
        return tradeGrouponService;
    }

3、解决办法

  • 改变量名 。 将变量名改成和容器中的beanId 相同即可;
    @Autowired
    private GrouponService tradeGrouponService;
  • 修改配置bean注入的地方,@Bean的方法名改成grouponService
    @Bean
    public GrouponService grouponService() {
        return grouponService;
    }

4、总结

  • @Bean 修饰方法时候,对应的beanId 取决于方法名;
  • @Autowire 默认的方式是按照setName的方式 ,当多个实现类存在于容器中,默认情况下引入的beanId 等同于字段名
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值