javascript
Spring注入bean报错:Error creating bean with name的网上找不到的解决方案
今天在研究BaseService,在進行單元測試時,發現tomcat一直報錯,錯誤代碼如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘這是我的service測試類’: Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [這是我的service類] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
從信息中,可以看到是找不到需要注入的bean!我的程序是通過注解@Resource注入的。
嘗試了網上的N種方法,無非以下幾種:
但是問題依然存在,我就開始去檢查需要注入的類有沒有問題,結果發現了。
@Transactional @Service("roomTypeService") public abstract class RoomTypeServiceImpl extends BaseServiceImpl<RoomType, Integer> implements RoomTypeService {// other fileds and methods...... }不知道小伙伴們看出問題沒有,這里的Service注解和name都沒有問題,問題出在類寫成了抽象類!!!抽象類啊!!!我把它去掉了就能正常跑起來了!!
雖然我不知道為什么當時寫成了抽象類,但還是想分享出來讓跟我犯錯誤的同學盡快脫離debug的痛苦。
說回問題的本質,為什么寫成了抽象類就無法正常注入呢?這也正是java基礎知識:注入相當于實例化一個對象,而在java的語法里面,抽象類(和接口)是無法實例化(new)的,所以就注入失敗了!
好久沒寫過原創的文章了,這樣不行,說好的堅持呢= =
總結
以上是生活随笔為你收集整理的Spring注入bean报错:Error creating bean with name的网上找不到的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VMware的虚拟机连不上网
- 下一篇: gradle idea java ssm