Spring Boot一个非常突出的优点就是不需要我们额外再部署Servlet容器,它内置了多种容器的支持。我们可以通过配置来指定我们需要的容器。
本文以我们平时最常使用的容器Tomcat为列来介绍以下两个知识点:
- Spring Boot是怎么整合启动Tomcat容器的;
- 在Spring Boot中,怎么进行Tomcat的深度配置。
Spring Boot整合启动Tomcat的流程
对于看源代码,每个人都有自己的方法。我自己在看源代码的时候喜欢结合IDEA的Debug功能一起看。比如说现在我们要研究Spring Boot是在哪个环节点启动Tomcat的,
我的思路是:Tomcat在启动时会调用各个组件的init方法和start方法,那么我只需要在这些方法上打上端点,然后就能在调用栈上看出Spring Boot是在哪个环节点启用
Tomcat的了。
按照这个思路,我在Tomcat的Connector组件的init方法上打了端点,通过调用栈能很清楚的看出Spring Boot是在容器的onRefresh方法中调用Tomcat的。
protected void onRefresh() {
super.onRefresh();
try {
this.createWebServer();
} catch (Throwable var2) {
throw new ApplicationContextException("Unable to start web server", var2);
}
}
![c7099b19e4530e0a81c3bf0e8e1611e8.png](https://i-blog.csdnimg.cn/blog_migrate/d3dd129da072314b88b5de2b6da05845.jpeg)
找到了调用点,那么一切都好办了。从上面的方法中可以看出,重点内容就在this.createWebServer()这个方法中。
在Spring Boot中使用的容器类是ServletWebServerApplicationContext系列的容器,这个系列的容器可以内嵌Web容器。这个我们
可以从这个容器的属性和方法中可以看出来。
public class ServletWebServerApplicationContext extends GenericWebApplicationContext implements ConfigurableWebServerApplicationContext {
//...省略部分代码
public static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet";
//内嵌容器
private volatile WebServer webServer;
private ServletConfig servletConfig;
//...省略部分代码
//创建Web容器
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = this.getServletContext();
//webServer和servletContext都是null,表示还没创建容器,进入创建容器的逻辑
if (webServer == null && servletContext == null) {
//获取创建容器的工厂,可以通过WebServerFactoryCustomizer接口对这个工厂进行自定义设置
Serv