SpringBoot中如何启动Tomcat流程
SpringBoot 项目之所以部署简单,其很大一部分原因就是因为不用自己折腾 Tomcat 相关配置,因为其本身内置了各种 Servlet 容器。一直好奇: SpringBoot 是怎么通过简单运行一个 main 函数,就能将容器启动起来,并将自身部署到其上 。此文想梳理清楚这个问题。
我们从SpringBoot的启动入口中分析:
Context 创建
// Create, load, refresh and run the ApplicationContext
context = createApplicationContext();
在SpringBoot 的 run 方法中,我们发现其中很重要的一步就是上面的一行代码。注释也写的很清楚:
创建、加载、刷新、运行 ApplicationContext。
继续往里面走。
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
contextClass = Class.forName(this.webEnvironment
? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}
逻辑很清楚:
先找到 context 类,然后利用工具方法将其实例化。
其中 第5行 有个判断:如果是 web 环境,则加载 DEFAULT _WEB_CONTEXT_CLASS类。参看成员变量定义,其类名为:
AnnotationConfigEmbeddedWebApplicationContext
此类的继承结构如图:
直接继承 GenericWebApplicationContext。关于该类前文已有介绍,只要记得它是专门为 web application提供context 的就好。
refresh
在经历过 Context 的创建以及Context的一系列初始化之后,调用 Context 的 refresh 方法,真正的好戏才开始上演。
从前面我们可以看到AnnotationConfigEmbeddedWebApplicationContext的继承结构,调用该类的refresh方法,最终会由其直接父类:EmbeddedWebApplicationContext 来执行。
@Override
protected void onRefresh() {
super.onRefresh();
try {
createEmbeddedServletContainer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start embedded container",
ex);
}
}
我们重点看第5行。
private void createEmbeddedServletContainer() {
EmbeddedServletContainer localContainer = this.embeddedServletContainer;
ServletContext localServletContext = getServletContext();
if (localContainer == null && localServletContext == null) {
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
this.embeddedServletContainer = containerFactory
.getEmbeddedServletContainer(getSelfInitializer());
}
else if (localServletContext != null) {
try {
getSelfInitializer().onStartup(localServletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context",
ex);
}
}
initPropertySources();
}
代码第5行,获取到了一个EmbeddedServletContainerFactory,顾名思义,其作用就是为了下一步创建一个嵌入式的 servlet 容器:EmbeddedServletContainer。
public interface EmbeddedServletContainerFactory {
/**
* 创建一个配置完全的但是目前还处于“pause”状态的实例.
* 只有其 start 方法被调用后,Client 才能与其建立连接。
*/
EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers);
}
第6、7行,在 containerFactory 获取EmbeddedServletContainer的时候,参数为 getSelfInitializer 函数的执行结果。暂时不管其内部机制如何,只要知道它会返回一个 ServletContextInitializer 用于容器初始化的对象即可,我们继续往下看。