No unique bean of type

来源:互联网 发布:山东油罐车物流软件 编辑:程序博客网 时间:2024/05/22 00:52

使用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的实现类。

@Servicepublic class UnitServiceImpl implements UnitService {@ResourceUnitDAO 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


0 0