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 等同于字段名