WebServer 初始化过程
在上一节中 Spring Boot 初始化了 WebServer 对应的工厂类。同时,我们也知道对应 Web容器的WebServer实现类有:TomcatWebServer、JettyWebServer和UndertowWebServer。
这节重点讲解这些 WebServer 是如何被初始化,又如何启动的。
WebServer 接口的源代码如下。
public interface WebServer {
void start() throws WebServerException;
void stop() throws WebServerException;int getPort();
}
接口定义了 3 个方法: start 方 法为启动容器,stop 方 法为停止容器,getPort 方法为获得容器端口。
现在以 Tomcat 的启动为例来说明整个内置容器的加载与启动。在上节中,工厂类已经被自动配置初始化。那么,在什么地方用到它们的呢?这要回到最初 Spring Boot 启动的过程中。
还记得 SpringApplication 的 run 方法中有一个调用初始化容器的方法 refreshContext 吗?
我们就从这个方法开始追踪。
public ConfigurableApplicationContext run(String... args) {
try {
//初始化容器
refreshContext(context);
} catch (Throwable ex) {
}
在 run 方法中调用了 refreshContext 方法,refreshContext 方法中又调用了refresh 方法。
private void refreshContext(ConfigurableApplicationContext context) {
//调用 refresh 方法
refresh(context);
refresh 方法的代码如下。
protected void refresh(ApplicationContext applicationContext) {
Assert. isInstanceOf(AbstractApplicat ionContext. class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
通过 refresh 方法我们能看到什么呢?对的,就是
AbstractApplicationContext 这个抽象类,该类的实例化对象在调用 refreshContext 方法之前,已经通过 createApplicationContext 方法进行实例化了。createApplicationContext 方法的源代码如下。
protected ConfigurableApplicat ionContext createApplicationContext() {
//首先获取容器的类变量
Class<?> contextClass = this . applicat ionContextClass;
/如果为 null,则根据 web 应用类型按照默认类进行创建
if (contextClass == null) {
try
witch (this . webApplicat ionType) {
contextClass = Class . forName(DEFAULT_ _SERVLET _WEB_ _CONTEXT_ CLASS);
break;
case REACTIVE:contextClass = Class . forName (DEFAULT_ REACTIVE_ WEB