问题场景描述
整个项目通过Maven构建,大致结构如下:
写了一个mapper、service一直提示无法注入:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [io.github.gefangshuai.rtat.service.RestaurantService] found for dependency: 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 24 more
总是提示无法注入Service或者Dao中的Bean!
解决分析
后来经研究发现,SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描!
“Application类”是指SpringBoot项目入口类。这个类的位置很关键:
如果Application类所在的包为:io.github.web.app,
则只会扫描io.github.web.app包及其所有子包,
如果service或dao所在包不在io.github.web.app及其子包下,则不会被扫描!
知道这一点非常关键,如果不知道还真是无从解决。