記錄 @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 模塊包名統一。
修改后問題解決。