springboot启动入口类:加载配置和启动

1.SpringBootApplication的背后

@SpringBootApplication整合三个最重要注解,看起来简洁。
1.1@Configuration
JavaConfig形式Spring Ioc容器配置类用的@Configuration,启动类标注了@Configuration之后,本身是IoC容器配置类。xml和注解实现bean的定义:

1.2@EnableAutoConfiguration

@EnableAutoConfiguration最关键作用@Import的支持,收集和注册特定场景相关bean定义。
@Import(EnableAutoConfigurationImportSelector.class),借助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration帮SpringBoot将所有符合条件@Configuration配置都加载到当前IoC容器。
借助于原有工具类:SpringFactoriesLoader智能自动配置

SpringFactoriesLoader:META-INF/spring.factories加载配置。将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射实例化,对应标注@Configuration的JavaConfig形式的IoC容器配置类,汇总并加载到IoC容器

2.springboot启动简单流程
1 运行SpringApplication的main的run()先实例化,初始化:
根据classpath下是否存在(ConfigurableWebApplicationContext)判断是否要启动web applicationContext
SpringFactoriesInstances加载classpath下所有可用的ApplicationContextInitializer
SpringFactoriesInstances加载classpath下所有可用的ApplicationListener

2 run()方法,遍历SpringApplicationRunListeners,调starting(),开始监听springApplication启动。

3 加载SpringBoot配置环境(ConfigurableEnvironment),如通过web容器发布加载StandardEnvironment。将配置环境(Environment)加入到监听器对象中(SpringApplicationRunListeners)。
4 banner属性的设置

5 ConfigurableApplicationContext(应用配置上下文)创建,根据webEnvironment是否是web环境创建默认的contextClass
,AnnotationConfigEmbeddedWebApplicationContext(通过扫描所有注解类来加载bean)和ConfigurableWebApplicationContext),BeanUtils实例化上下文对象返回。

6 prepareContext()将listeners、environment、applicationArguments、banner等重要组件与上下文对象关联

1.3.7 refreshContext(context),bean的实例化完成IoC容器可用的最后一道工序。

网友评论