目录
@SpringbootApplication(主入口)
- @SpringBootApplication
- public class SpringbootConfigApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringbootConfigApplication.class, args);
- }
-
- }
标注在某个类上说明是springboot的主启动类,springboot运行这个类的main方法来启动springboot应用。是springboot的核心配置文件,其中包含
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
自动扫描并加载符合条件的组件或bean,对应原先XML中的元素,将bean注入IOC容器中
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Configuration
- @Indexed
- public @interface SpringBootConfiguration {
- @AliasFor(
- annotation = Configuration.class
- )
- boolean proxyBeanMethods() default true;
- }
作用:标注在某个类上,就作为springboot的配置类,点击Configuration继续进入注解。
- // 点进去得到下面的 @Component
- @Configuration
- public @interface SpringBootConfiguration {}
-
- @Component
- public @interface Configuration {}
@EnableAutoConfiguration告诉SpringBoot开启自动配置功能,这样自动配置才能生效
1.AutoConfigurationPackage:自动配置包
@Import({Registrar.class}) public @interface AutoConfigurationPackage { }1.1 @Import导入一个容器组件
1.2 Registrar.class:将启动类同级下的包和他的子包都加载到spring容器中
2.@Import({AutoConfigurationImportSelector.class}):给容器导入组件
点击源码进入AutoConfigurationImportSelector:
- // 获得候选的配置
- protected List
getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { - //这里的getSpringFactoriesLoaderFactoryClass()方法
- //返回的就是我们最开始看的启动自动导入配置文件的注解类;EnableAutoConfiguration
- List
configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()); - Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
- return configurations;
- }
- public static List
loadFactoryNames(Class> factoryClass, @Nullable ClassLoader classLoader) { - String factoryClassName = factoryClass.getName();
- //这里它又调用了 loadSpringFactories 方法
- return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
- }
Enumeration urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");

SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值
将这些值作为自动配置类导入容器 , 自动配置类就生效
