SpringBoot-启动原理
Spring启动时做了哪些事
1 | |
可以看出SpringBoot启动的过程可以分成2步
1、new SpringApplication()
1 | |
- 记录springboot启动类
- 判断SpringBoot启动环境是否web
- 从META-INF/spring.factories 获取应用BootstrapRegistryInitializer初始化器
- 从META-INF/spring.factories 获取应用上下文ApplicationContextInitializer初始化器
- 从META-INF/spring.factories 获取应用监听器
- 获取springboot启动类main方法所在类
2、SpringApplication.run
1 | |
SpringBoot启动的2种方式
jar包
本质:SpringBoot启动带动内置tomcat启动
简述:SpringApplication.run
->新建ioc
-> 容器刷新
-> onrefresh方法
->ServletWebServerApplicationContext
ServletWebServerFactory factory = getWebServerFactory();
factory.getWebServer(getSelfInitializer());
jar启动流程
war包
本质:tomcat启动带动SpringBoot启动(Servlet3.0特性 tomcat启动会创建)
8.2.4 Shared libraries / runtimes pluggability
The ServletContainerInitializer class is looked up via the jar services API. For each application, an instance of the ServletContainerInitializer is created by the container at application startup time. The framework providing an implementation of the ServletContainerInitializer MUST bundle in the META-INF/services directory of the jar file a file called javax.servlet.ServletContainerInitializer, as per the jar services API,that points to the implementation class of the ServletContainerInitializer. In addition to the ServletContainerInitializer we also have an annotation -HandlesTypes. The HandlesTypes annotation on the implementation of the ServletContainerInitializer is used to express interest in classes that may have annotations (type, method or field level annotations) specified in the value of the HandlesTypes or if it extends / implements one those classes anywhere in the class’ super types. The HandlesTypes annotation is applied irrespective of the setting of metadata-complete.1.1)web应用启动,会创建当前Web应用导入jar包中 的 ServletContainerInitializer类的实例
1.2)ServletContainerInitializer 类必须放在jar包的 META-INF/services目录 下,文件名称为 javax.servlet.ServletContainerInitializer
1.3)文件的内容指向ServletContainerInitializer实现类的全路径
1.4)使用@HandlesTypes 在我们应用启动的时候,加载我们感兴趣的类
1.5)spring-web 配置了tomcat启动时要创建的实例类

1
2@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
简述:Tomcat启动->
SpringServletContainerInitializer.onStartup
->SpringBootServletInitializer.onStartup
->WebApplicationContext rootApplicationContext = createRootApplicationContext(servletContext)
->run(application) 触发SpringBoot启动