【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的配置,让程序员更加专注于业务的开发。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值