No unique bean of type

使用webx开发时遇到几次这样的错误,总结一下。

在applicationContext.xml里面添加定时器任务的配置:

 <bean name="applicationService" class="com.taobao.scm.tenv.monitor.service.impl.ApplicationServiceImpl" />
    <bean name="productService" class="com.taobao.scm.tenv.monitor.service.impl.ProductServiceImpl" /> 
    <bean name="buService" class="com.taobao.scm.tenv.monitor.service.impl.BuServiceImpl" />  
    
    <bean name="unitService" class="com.taobao.scm.tenv.service.impl.UnitServiceImpl" />  
最后一行,加了一个unitService的bean。 这个 bean 是一个现有 Service 的实现类。

@Service
public class UnitServiceImpl implements UnitService {
	@Resource
	UnitDAO unitDao;
	
	public List<UnitDO> findUnitByCondition(UnitDO unitDO){
		return unitDao.findListByExample(unitDO);
	}
}

如上所示,我这里是用了注解@Servicespring会自动加载这个类。编译,结果报如下错误:

2015-06-08 17:22:03.777:WARN::Failed startup of context runjettyrun.HSFJettyWebAppContext@19c2921d{/,src/main/webapp}

org.springframework.beans.factory.BeanCreationException

Error creating bean with name 'module.screen.MachineApply': Injection of resource dependencies failed; 

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException

No unique bean of type [com.taobao.scm.tenv.service.interfaces.UnitService] is defined: 

expected single matching bean but found 2: [unitServiceImpl, unitService]

根据错误信息定位到module.screen.MachineApply这个文件,发现了如下定义:

public class MachineApply {
	  
	  @Resource
	  UserService userService;
	  
	  @Resource
	  MachineService machineService;
	  
	  @Resource
	  MirrorService mirrorService;
	  
	  @Resource
	  SpecificationService specificationService;
	  
	  @Resource
	  UnitService unitservice;
	  
最后一行,@Resource了一个UnitServer unitservice。问题就出在这里的命名, spring 初始化 bean 时,会监测要初始化的 bean 是否已经存在相同名称的 bean,applicationContext.xml里面的命名是unitService,而MachineApply.java里面是unitservice,故这个bean被加载了2次,造成冲突。解决方式是:

1,将MachineApply.java里面是unitservice改成规范型的unitService。(推荐)

2,将applicationContext.xml里面的unitService改成unitservice。(不推荐,如果java文件中其他地方也有用到这个,都要统一改,所以规范的命名是很重要的)

这次命名的不规范踩了一个大坑,同时也对这个bean的加载过程有了一点了解。结合网上的分析,总结如下:

1. @Service在声明bean的时候如果不指定名称的话,会默认以类名的一个字母小写命名。

2. 当spring初始化bean时,会监测要初始化的bean是否已经存在相同名称的bean。

3. spring初始化bean的顺序依赖于你在xml里面配置的顺序。

4.spring在初始化bean的时候是只保持名称的一致性。


附上另一篇文件的分析: http://mixer-b.iteye.com/blog/1563851


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值