【SpringBoot源码阅读】Springboot启动tomcat原理

Springboot启动tomcat原理

一:思考

​ 记得以前SSM项目时候,需要把项目打包到tomcat的webApps目录下。然后启动tomcat。

现在springboot项目直接打包成jar宝就可以启动tomcat了。Springboot为了实现这个功能做了那些操作,和设计呢?

二:源码探索

我们从SpringBoot的启动类的run()方法中去。

进入方法,我们看到一个关键的类,这个个方法就是Spring上下文的类的类路径。

这个的webApplicationType 的值就是SERVLET (什么时候赋值,后面再说),返回的类就是可以作为理解tomcat启动的突破口。

我们看这个类的结构图

这个类就是基础beanFactory接口,就是我们spring的上下文增强子类。

可以看到,我们重新实现了onRefresh()方法。

增加要给createWebServer()方法,我们看这个名字猜测就是和tomcat 有关。

我们看getWebServerFactory();方法,创建一个web服务器工厂类,点进去方法,我们发现,通过类型再spring容器中取

// Use bean names so that we don't consider the hierarchy
		String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
		if (beanNames.length == 0) {
			throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing "
					+ "ServletWebServerFactory bean.");
		}
		if (beanNames.length > 1) {
			throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "
					+ "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
		}
		return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);

那这几个工厂类什么时候注入的呢?,我们全局搜索关键字发现,再ServletWebServerFactoryAutoConfiguration中通过@Bean注解注入了我们的工厂类TomcatServletWebServerFactoryCustomizer

我们呢继续跟进方法

this.webServer = factory.getWebServer(getSelfInitializer());

我们看到初始化了tomcat,同时启动了tomcat,这样再我们spring容器启动后,通过``createWebServer` 启动了tomcat。

再启动之前还有很多tomcat启动参数设置,这些这里省略了,感兴趣的可以继续研究一下。

三:总结

SpringBoot 利用spring的拓展特性,再spring容器启动后,启动tomcat。简化和tomcat的配置,让程序员更加专注于业务的开发。

posted @ 2021-06-05 21:11  一懒众衫小QAQ  阅读(235)  评论(0编辑  收藏  举报