那么在 Spring boot 项目中,应用上下文又是如何找到那么多配置并加载初始化好的呢?
@SpringBootApplication
spring boot 项目推荐大家在主类中标注 @SpringBootApplication 这个注解,我们来看看它的源码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration // 配置
@EnableAutoConfiguration // 启用自动配置
// 组件扫描
@ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))
public @interface SpringBootApplication {
// 需要排除的自动配置类
Class<?>[] exclude() default {};
// 需要排除的自动配置类类名
String[] excludeName() default {};
// 扫描包路径
@AliasFor(annotation = ComponentScan.class, attribute = “basePackages”)
String[] scanBasePackages() default {};
// 扫描包路径类
@AliasFor(annotation = ComponentScan.class, attribute = “basePackageClasses”)
Class<?>[] scanBasePackageClasses() default {};
}
@EnableAutoConfiguration
我们发现一个配置开关注解,名字叫 @EnableAutoConfiguration,看看它的源码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
// 是否启用自动配置的总开关名
String ENABLED_OVERRIDE_PROPERTY = “spring.boot.enableautoconfiguration”;
// 需要排除的自动配置类
Class<?>[] exclude() default {};
// 需要排除的自动配置类类名
String[] excludeName() default {};
}
EnableAutoConfigurationImportSelector
我们看到有一个 @Import 导入了选择器 EnableAutoConfigurationImportSelector.class,看看它的源码:
public class EnableAutoConfigurationImportSelector
implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
BeanFactoryAware, EnvironmentAware, Ordered {
…