SpringBoot bean無法注入
阿新 • • 發佈:2019-01-02
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userP in com.springboot.controller.UserController required a bean of type 'com.springboot.model.UserProperties' that could not be found.
Action:
APPLICATION FAILED TO START
***************************
Description:
Field userP in com.springboot.controller.UserController required a bean of type 'com.springboot.model.UserProperties' that could not be found.
Action:
Consider defining a bean of type 'com.springboot.model.UserProperties' in your configuration.
SpringBoot專案的Bean裝配預設規則是根據Application類所在的包位置從上往下掃描!
“Application類”是指SpringBoot專案入口類。這個類的位置很關鍵:
如果Application類所在的包為:com.springboot.controller
,則只會掃描com.springboot.controller
包及其所有子包,如果service或dao所在包不在com.springboot.controller
及其子包下,則不會被掃描!
故此Application類應該放在父包com.springboot中,這樣就能掃描到com.springboot.controller,service,dao包裡的bean了。
Spring
Boot預設會掃描啟動類同包以及子包下的註解,那麼如何進行改變這種掃描包的方式呢,原理很簡單就是:
@ComponentScan註解進行指定要掃描的包以及要掃描的類。
- @ComponentScan(basePackages={"com","com.hha"})