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)
無(wú)法注入Dao中的Bean棘脐!
解決分析后來(lái)經(jīng)研究發(fā)現(xiàn)龙致,SpringBoot項(xiàng)目的Bean裝配默認(rèn)規(guī)則是根據(jù)Application類(lèi)所在的包位置從上往下掃描! “Application類(lèi)”是指SpringBoot項(xiàng)目入口類(lèi)目代。這個(gè)類(lèi)的位置很關(guān)鍵:
如果Application類(lèi)所在的包為:io.github.gefangshuai.app
,則只會(huì)掃描io.github.gefangshuai.app
包及其所有子包在讶,如果service或dao所在包不在io.github.gefangshuai.app
及其子包下霜大,則不會(huì)被掃描构哺!
知道這一點(diǎn)非常關(guān)鍵,不知道Spring文檔里有沒(méi)有給出說(shuō)明曙强,如果不知道還真是無(wú)從解決。
轉(zhuǎn):http://blog.csdn.net/gefangshuai/article/details/50328451,http://412887952-qq-com.iteye.com/blog/2292733
在開(kāi)發(fā)中我們知道Spring Boot默認(rèn)會(huì)掃描啟動(dòng)類(lèi)同包以及子包下的注解溪食,那么如何進(jìn)行改變這種掃描包的方式呢娜扇,原理很簡(jiǎn)單就是:@ComponentScan注解進(jìn)行指定要掃描的包以及要掃描的類(lèi)错沃。