天天看点

SpringBoot项目中tomcat容器启动流程

作者:九阳开太

1.项目启动类的main方法执行

SpringBoot项目中tomcat容器启动流程

2.执行run方法

经过一系列run的重载方法后,最终调到org.springframework.boot.SpringApplication#run

SpringBoot项目中tomcat容器启动流程

3.Spring容器初始化

执行前置方法后,调用org.springframework.boot.SpringApplication#refreshContext解析配置类,启动WebServer,最终调用Spring定义的接口方法:org.springframework.context.ConfigurableApplicationContext#refresh,ConfigurableApplicationContext在SpringBoot中有二个实现类ServletWebServerApplicationContext和ReactiveWebServerApplicationContext

SpringBoot项目中tomcat容器启动流程

此处调用的是org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#refresh,实际调用的是Spring提供抽象父类的方法org.springframework.context.support.AbstractApplicationContext#refresh

SpringBoot项目中tomcat容器启动流程

4.Spring容器初始化后的回调

spring容器启动完成后,会调用onRefresh方法,实际调用的是SpringBoot提供的子类中的方法org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh

SpringBoot项目中tomcat容器启动流程

5.创建WebServer

org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServer

SpringBoot项目中tomcat容器启动流程

6.获取WebServerFactory

org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#getWebServerFactory

SpringBoot项目中tomcat容器启动流程

ServletWebServerFactory接口有多个实现类,下面标红的3个就是常用的三个web容器(tomcat/jetty/undertom),启动tomcat用的是TomcatServletWebServerFactory

SpringBoot项目中tomcat容器启动流程

7.获取WebServer,创建并设置Tomcat相关对象属性

org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer

SpringBoot项目中tomcat容器启动流程

8.封装TomcatWebServer

org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getTomcatWebServer

SpringBoot项目中tomcat容器启动流程

9.初始化TomcatWebServer并启动Tomcat

org.springframework.boot.web.embedded.tomcat.TomcatWebServer#TomcatWebServer

SpringBoot项目中tomcat容器启动流程