springBoot 原理
Annotation 定 义 ( @SpringBootApplication ) 和 类 定 义 ( SpringApplication.run ) ;
@SpringBootApplication
主要分为三个核心
1.
2.
3.
@Configuration
@EnableAutoConfiguration
@ComponentScan
注解解析
@Configuration
JavaConfig 形式的 Spring Ioc 容器的配置类使用的那个@Configuration(主要对比的是基于 xml 的配置)
@Configuration 相当于
@bean 相当于
@EnableAutoConfiguration
SpringBoot 核心,先看源码
@Enable 开头的 Annotation 定义,借助@Import 的支持,收集和注册特定场景相关的 bean 定义
例如 :@EnableScheduling 是通过@Import 将 Spring 调度框架相关的 bean 定义都加载到 IoC 容器。
@EnableAutoConfiguration 也是借助@Import 的帮助,将所有符合自动配置条件的 bean 定义加载到 IoC 容
器
从源码中看到@EnableAutoConfiguration 最大的依赖就是借助@AutoConfigurationImportSelector 将所
有符合条件的@Configration 的配置类加载到当前的 spingIoc 容器中。
其中,能够自动的配置各种@Configuration 配置类还需要 spring 的工具类 SpringFactoriesLoader
SpringFactoriesLoader 原理:从指定的配置文件 META-INF/spring.factories 加载配置。
总结:@EnableAutoConfiguration 就是从指定的配置文件中加载其中的配置项,通过 java 反射的机
制实例化这些对象,把带有@Configuration 形式的 javaconfig 配置加载到当前的 spring 容器中。
@ComponentScan
其实就是自动扫描并加载符合条件的组件或者 bean 定义,最终将这些 bean 定义加载到 IoC 容器中。默认
Spring 框架实现会从声明@ComponentScan 所在类的 package 进行扫描。
运行过程
springFactoriesloader 加载 SpringApplicationRunListener,并执行 start 方法
a.
b. 配置环境,遍历所有的 SpringApplicationRunListener 执行 environmentPrepared 方法
c. 把环境交给 ApplicationContext
d.
e. 遍历 SpringApplicationRunListener 的 contextPrepared()方法。
f. 将之前通过@EnableAutoConfiguration 获取的所有配置以及其他形式的 IoC 容器配置加载到已经准
springFactoriesloader 加载 ApplicationContext-Initializer,并执行 initialize 方法
备完毕的 ApplicationContext
ApplicationContext 的 refresh()方法
g. 遍历调用所有 SpringApplicationRunListener 的 contextLoaded()方法。
h.
监听 start 方法===》配置环境,监听 environmentPrepared 方法====》环境交给 ApplicationContext====》
上下文 initialize 方法====》监听 contextPrepared 方法==》加载@EnableAutoConfiguration 配置===》
监听 contextLoaded 方法===》ApplicationContext 的 refresh()方法