本文通过阅读SpringBoot源码,分享SpringBoot中Tomcat,SpringMvc组件的启动过程。
源码分析基于spring boot 2.1
Tomcat
在解析SpringBoot启动的文章中说过,SERVLET应用使用的ApplicationContext是AnnotationConfigServletWebServerApplicationContext。
其父类ServletWebServerApplicationContext,通过ServletWebServerFactory创建并初始化WebServer,WebServer兼容不同的servlet容器(tomcat,jetty,netty),提供统一的start,stop操作。
ServletWebServerApplicationContext还负责注册Servlet,Filter,ServletContextListener的工作。
ServletWebServerApplicationContext#servletConfig,GenericWebApplicationContext#servletContext都是servlet规范提供的类。
ApplicationContext#run -> AnnotationConfigServletWebServerApplicationContext#refresh -> AbstractApplicationContext#refresh -> AbstractApplicationContext#onRefresh -> ServletWebServerApplicationContext#onRefresh -> ServletWebServerApplicationContext#createWebServer
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
// #1
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
// #2
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
#1
创建webServer,注意getSelfInitializer()通过方法引用构造了一个ServletContextInitializer,该ServletContextInitializer会调用ServletWebServerApplicationContext#selfInitialize方法#2
webServer已经存在,直接调用ServletWebServerApplicationContext#selfInitialize
ServletWebServerFactoryConfiguration中判断当前JAVA环境中存在的servlet容器依赖,构造对应的WebServerFactory。
这里只关注tomcat。
TomcatServletWebServerFactory#getWebServer
public WebServer getWebServer(ServletContextInitializer... initializers) {
// #1
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
// #2
prepareContext(tomcat.getHost(), initializers);
// #3
return getTomcatWebServer(tomcat);
}
#1
构造Tomcat对象,并配置相关属性 #2
对Tomcat Context做一个预先配置#3
转化为Spring的TomcatWebServer对象
#2
步骤会构造一个TomcatStarter,TomcatStarter是一个ServletContainerInitializer实现类。ServletContainerInitializer也是servlet规范提供的类,servlet容器启动后调用ServletContainerInitializer#onStartup。
TomcatStarter#initializers是ServletContextInitializer数组, TomcatStarter#onStartup会遍历该数组,调用ServletContextInitializer#onStartup。
ServletWebServerApplicationContext#createWebServer方法#1
步骤调用getSelfInitializer()方法构造了一个ServletContextInitializer,该ServletContextInitializer一直传递给TomcatServletWebServerFactory#getWebServer,并用于构造TomcatStarter。
所以tomcat启动后最终会调用ServletWebServerApplicationContext#selfInitialize
private void selfInitialize(ServletContext servletContext) throws ServletException {
// #1
prepareWebApplicationContext(servletContext);
registerApplicationScope(servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);
// #2
for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
beans.onStartup(servletContext);
}
}
#1
从ServletContext获取相关属性,并设置到SpringContext中。#2
查找Spring上下文中的ServletContextInitializer,并调用onStartup方法。
ServletContextInitializer是一个配置接口,通过编程的方式配置Servlet 3.0+ ServletContext。
它的实现类FilterRegistrationBean,ServletRegistrationBean,ServletListenerRegistrationBean 可以向ServletContext注入Filter,Servlet,ServletContextListener。
TomcatWebServer#构造函数 -> TomcatWebServer#initialize
private void initialize() throws WebServerException {
// #1
logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
synchronized (this.monitor) {
try {
addInstanceIdToEngineName();
// #2
Context context = findContext();
context.addLifecycleListener((event) -> {
if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
removeServiceConnectors();
}
});
// #3
this.tomcat.start();
rethrowDeferredStartupExceptions();
// #4
try {
ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
}
catch (NamingException ex) {
// Naming is not enabled. Continue
}
// #5
startDaemonAwaitThread();
}
catch (Exception ex) {
stopSilently();
destroySilently();
throw new WebServerException("Unable to start embedded Tomcat", ex);
}
}
}
#1
打印Tomcat启动日志#2
获取Tomcat Context,并配置相关属性#3
启动Tomcat,并调用ServletContainerInitializer#onStartup#4
绑定ClassLoader#5
因为所有tomcat线程都是后台线程,所以要创建一个阻塞的非后台线程保持进程。
SpringMVC
SpringMVC组件的启动就比较简单了。
WebMvcAutoConfiguration负责构造RequestMappingHandlerAdapter,HandlerMethodReturnValueHandler,HttpMessageConverter,RequestMappingHandlerMapping等组件
DispatcherServletAutoConfiguration负责构造DispatcherServlet组件
关于SpringMVC,可以参考之前的文章 -- Spring Mvc原理
DispatcherServletAutoConfiguration中使用DispatcherServletRegistrationBean将DispatcherServlet注册到ServletContext,DispatcherServletRegistrationBean继承了ServletRegistrationBean,最后由ServletWebServerApplicationContext#selfInitialize完成注入操作。
@WebFilter,@WebListener,@WebServlet也可以注入Servlet,Filter,ServletContextListener。(这三个接口都是servlet规范提供的)
这些注解由@ServletComponentScan注解处理,@ServletComponentScan注解通过@Import引入ServletComponentScanRegistrar,ServletComponentScanRegistrar实现了ImportBeanDefinitionRegistrar(关于ImportBeanDefinitionRegistrar接口,可以回顾之前解析SpringBoot AutoConfigure的文章),ServletComponentScanRegistrar#registerBeanDefinitions引入了ServletComponentRegisteringPostProcessor,
该PostProcessor扫描对应目录下的@WebFilter,@WebListener,@WebServlet注解,使用对应的ServletComponentHandler进行处理。有兴趣的同学可以自行阅读代码。