1. 为什么扫描包的时候默认扫描主启动类所在的包?
如题,在开发中,一般要求标注 @Component
和 @Repository
等注解的类所在包要和主启动类同一个包,否则就要在主启动类配置 @ComponentScan
注解的 basePackages
来指定要扫描的包。
其实,问题的根源就在 @ComponentScan
注解上。
@ComponentScan
@ComponentScan
注解对应 Spring XML 配置形式中的 <context:component-scan>
元素,用于配合一些元信息 Java Annotation,比如 @Component
和 @Repository
等,将标注了这些元信息 Annotation 的 bean 定义类批量采集到 Spring 的 IoC 容器中。
参考《SpringBoot 揭秘》
而通过 basePackages 属性可以指定扫描包的范围,如果不指定,默认 Spring 框架实现会从声明 @ComponentScan
所在类的 package 进行扫描。
那么 SpringBoot 为什么能默认扫描到主启动类所在包下的 bean 呢?
其实对于 SpringBoot 而言,主启动类上的 @SpringBootApplication
注解整合了 @ComponentScan
注解,导致默认扫描的包为主启动类所在的包。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)})
public @interface SpringBootApplication