SpringBoot启动流程主要分为两个步骤
一、创建SpringApplication对象。
二、调用SpringApplication对象的run()方法实现启动,并且返回当前容器的上下文。
流程详解:
一、创建SpringApplication对象,SpringBoot容器的初始化操作。
二、获取当前应用的启动类型。
原理:判断当前classpath是否有加载servlet类。
WebApplicationType分为三种类型
- REACTIVE:响应式启动(Spring5的新特性)
- NONE:不会嵌入WEB容器启动
- SERVLET:基于WEB容器启动
三、setInitializers读取springboot包下的META-INF/spring.factories获取到对应的ApplicationContextInitializer装配到集合中
四、setListeners读取springboot包下面的META-INF/spring.factories获取到对应的ApplicationListener装配到集合中
五、mainApplicationClass获取当前运行的主函数
六、调用SpringApplication的run()方法实现启动
七、stopWatch.start();开始记录项目的启动时间
八、getRunListeners(args);读取META-INF/spring.factories,将SpringApplicationRunListeners类型存入带集合中
九、listeners.starting();循环调用starting()方法
十、ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
listeners.environmentPrepared(environment);循环读取配置文件到springboot容器中,因为配置文件可以自定义,就会存在多个。
十一、Banner printedBanner = printBanner(environment);打印Springboot启动标志
十二、context = createApplicationContext();创建springboot上下文
十三、prepareContext(context, environment, listeners, applicationArguments, printedBanner);为springboot上下文设置environment属性。
十四、refreshContext(context);刷新上下文
十五、开始创建Tomcat容器
十六、开始加载SpringMVC
十七、afterRefresh(context,applicationArguments);定义一个空的模板给其他子类实现重写
十八、listeners.started(context);使用广播和回调机制通知监听器springboot容器启动成功
十九、listeners.running(context);使用广播和回调机制通知监听器springboot容器已成功running
二十、最后返回当前的上下文
ps:该内容由蚂蚁课堂余老师视频讲解,非常感谢