关于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
及其子包下,则不会被扫描!

知道这一点非常关键,不知道Spring文档里有没有给出说明,如果不知道还真是无从解决。
转:http://blog.csdn.net/gefangshuai/article/details/50328451,http://412887952-qq-com.iteye.com/blog/2292733
在开发中我们知道Spring Boot默认会扫描启动类同包以及子包下的注解,那么如何进行改变这种扫描包的方式呢,原理很简单就是:@ComponentScan注解进行指定要扫描的包以及要扫描的类。

参考:http://blog.csdn.net/u014695188/article/details/52263903

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容