SpringBoot内嵌Tomcat源码:
1、调用启动类SpringbootdemoApplication中的SpringApplication.run()方法。
@SpringBootApplication
public class SpringbootdemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootdemoApplication.class, args);}
}
2、构建完SpringApplication对象后,调用其run方法,重点关注该方法中的refreshContext(context)方法
public ConfigurableApplicationContext run(String... args) {......refreshContext(context);......return context;}
private void refreshContext(ConfigurableApplicationContext context) {if (this.registerShutdownHook) {shutdownHook.registerApplicationContext(context);}refresh(context);}
调用SpringApplication中refreshContext()方法的refresh(context);调用ConfigurableApplicationContext 的子类ServletWebServerApplicationContext中实现的refresh()方法。
protected void refresh(ConfigurableApplicationContext applicationContext) {applicationContext.refresh();}
ServletWebServerApplicationContext中实现的refresh()方法,该方法内部调用了其父类AbstractApplicationContext中的refresh()方法。
@Overridepublic final void refresh() throws BeansException, IllegalStateException {try {super.refresh();}catch (RuntimeException ex) {WebServer webServer = this.webServer;if (webServer != null) {webServer.stop();}throw ex;}}
重点关注AbstractApplicationContext中的this.onRefresh(),该方法是一个空方法,交给子类ServletWebServerApplicationContext实现,createWebServer()方法创建web服务器。
@Overrideprotected void onRefresh() {super.onRefresh();try {createWebServer();}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}}
private void createWebServer() {//TomcatWebServerWebServer webServer = this.webServerServletContext servletContext = this.getServletContext();if (webServer == null && servletContext == null) {//创建WebServer步骤,并标志着他开始StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");//通过BeanName为tomcatServletWebServerFactory获取ServletWebServerFactory(TomcatServletWebServerFactory)ServletWebServerFactory factory = this.getWebServerFactory();//添加一个StartUp,标记到步骤createWebServer.tag("factory", factory.getClass().toString());//从TomcatServletWebServerFactory工厂中获得TomcatWebServerthis.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});//TomcatWebServer创建完成createWebServer.end();//在DefaultListableBeanFactory中注册单例WebServerGracefulShutdownLifecycle(Web服务器的生命周期)this.getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer));//在DefaultListableBeanFactory中注册单例WebServerStartStopLifecycle(Web服务器启动-停止生命周期)this.getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, this.webServer));} else if (servletContext != null) {try {this.getSelfInitializer().onStartup(servletContext);} catch (ServletException var5) {throw new ApplicationContextException("Cannot initialize servlet context", var5);}}//初始化Servlet相关属性源(获取相关环境配置ConfigurableEnvironment)this.initPropertySources();}