首页 > 其他分享 >spring依赖注入单元测试:expected single matching bean but found 2

spring依赖注入单元测试:expected single matching bean but found 2

时间:2022-12-19 17:00:32浏览次数:64  
标签:UserDao Qualifier Autowired spring 单元测试 bean Spring userDao

异常信息:org.springframework.beans.factory.UnsatisfiedDependencyException:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.byd.mes.bussiness.service.siteoperation.activity.ExecuteActivityService] is defined: expected single matching bean but found 2: [executeActivityService, executeActivityForTesterService]

 

解决方案:

博文链接地址:​​http://haowei0315.javaeye.com/blog/444731​

@Qualifier 
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。 
1. 可能存在多个UserDao实例

 

1. @Autowired  
2. public void setUserDao(@Qualifier("userDao") UserDao userDao) {
3. this.userDao = userDao;
4. }

这样,Spring会找到id为userDao的bean进行装配。 
2. 可能不存在UserDao实例

 

1. @Autowired(required = false)  
2. public void setUserDao(UserDao userDao) {
3. this.userDao = userDao;
4. }


 



标签:UserDao,Qualifier,Autowired,spring,单元测试,bean,Spring,userDao
From: https://blog.51cto.com/u_15147537/5953077

相关文章