1. 程式人生 > >關於SpringBoot bean無法注入的問題(與檔案包位置有關)改變自動掃描的包

關於SpringBoot bean無法注入的問題(與檔案包位置有關)改變自動掃描的包

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.SpringBootJdbcDemoApplication.SpringBootJdbcDemoApplication': Unsatisfied dependency expressed through field 'userRepository': No qualifying bean of type [com.example.repositories.UserRepository] found for
dependency [com.example.repositories.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of
type [com.example.repositories.UserRepository] found for dependency [com.example.repositories.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569
) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)

無法注入Dao中的Bean!
解決分析後來經研究發現,SpringBoot專案的Bean裝配預設規則是根據Application類所在的包位置從上往下掃描! “Application類”是指SpringBoot專案入口類。這個類的位置很關鍵:
如果Application類所在的包為:io.github.gefangshuai.app
,則只會掃描io.github.gefangshuai.app
包及其所有子包,如果service或dao所在包不在io.github.gefangshuai.app
及其子包下,則不會被掃描!