使用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);
}
}
如上所示,我這裏是用了註解@Service,spring會自動加載這個類。編譯,結果報如下錯誤:
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的時候是隻保持名稱的一致性。