記錄 Spring Boot 中 @Autowired 注解無法自動注入的錯誤


記錄 @Autuwired 無法注入的原因,以及采用的解決方法

一、錯誤

idea 錯誤提示: (大概意思就是沒有掃描這個bean)

Could not autowire. No beans of 'HrService' type found.

具體描述:

Description:

Field hrService in com.hjx.pmsysweb.config.SecurityConfig required a bean of type 'com.hjx.pmsys.service.HrService' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.hjx.pmsys.service.HrService' in your configuration.

二、方法及原因

SpringBoot 項目的 Bean 裝配默認規則是根據 Application 類所在的包位置從上往下掃描!
“ Application 類”是指 SpringBoot 項目入口類。這個類的位置很關鍵:

如果 Application 類所在的包為:com.boot.app,則只會掃描 com.boot.app 包及其所有子包,
如果 service 或 dao 所在包不在 com.boot.app 及其子包下,則不會被掃描!
即, 把Application類放到 dao、service 所在包的上級,com.boot.Application 知道這一點非常關鍵

個人原因:包的路徑不統一,因為學習分模塊來建項目,在創建時沒有注意,以至於 Application 類所在包名,沒能與 Service 模塊包名統一。

修改后問題解決。

三、參考

spring boot 中@Autowired注解無法自動注入的錯誤


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM