Spring Boot如何启动嵌入式Tomcat?

本文已收录在Github关注我,紧跟本系列专栏文章,咱们下篇再续!

  • 🚀 魔都架构师 | 全网30W技术追随者
  • 🔧 大厂分布式系统/数据中台实战专家
  • 🏆 主导交易系统百万级流量调优 & 车联网平台架构
  • 🧠 AIGC应用开发先行者 | 区块链落地实践者
  • 🌍 以技术驱动创新,我们的征途是改变世界!
  • 👉 实战干货:编程严选网

0 前言

Spring Boot内部启动一个嵌入式Web容器。Tomcat是组件化设计,所以就是启动这些组件。

Tomcat独立部署模式是通过startup脚本启动,Tomcat的Bootstrap和Catalina负责初始化类加载器,并解析server.xml和启动这些组件。

内嵌模式

Bootstrap和Catalina的工作由Spring Boot代劳,Spring Boot调用Tomcat API启动这些组件。

1 Spring Boot中Web容器接口

1.1 WebServer

为支持各种Web容器,Spring Boot抽象出嵌入式Web容器,定义WebServer接口:

java 复制代码
public interface WebServer {

	void start() throws WebServerException;

	void stop() throws WebServerException;

	int getPort();

	/**
	 * Initiates a graceful shutdown of the web server. Handling of new requests is
	 * prevented and the given {@code callback} is invoked at the end of the attempt. The
	 * attempt can be explicitly ended by invoking {@link #stop}. The default
	 * implementation invokes the callback immediately with
	 * {@link GracefulShutdownResult#IMMEDIATE}, i.e. no attempt is made at a graceful
	 * shutdown.
	 * @param callback the callback to invoke when the graceful shutdown completes
	 * @since 2.3.0
	 */
	default void shutDownGracefully(GracefulShutdownCallback callback) {
		callback.shutdownComplete(GracefulShutdownResult.IMMEDIATE);
	}

	default void destroy() {
		stop();
	}

}

Web容器比如Tomcat去实现该接口

1.2 ServletWebServerFactory

创建Web容器,返回的就是WebServer。

java 复制代码
public interface ServletWebServerFactory {
    WebServer getWebServer(ServletContextInitializer... initializers);
}

ServletContextInitializer入参表示ServletContext的初始化器,用于ServletContext中的一些配置:

java 复制代码
public interface ServletContextInitializer {
    void onStartup(ServletContext servletContext) throws ServletException;
}

getWebServer会调用ServletContextInitializer#onStartup,即若想在Servlet容器启动时做一些事情,如注册自己的Servlet,可实现一个ServletContextInitializer,在Web容器启动时,Spring Boot会把所有实现ServletContextInitializer接口的类收集起来,统一调其onStartup。

1.3 WebServerFactoryCustomizerBeanPostProcessor

一个BeanPostProcessor,为定制化嵌入式Web容器,在postProcessBeforeInitialization过程去寻找Spring容器中WebServerFactoryCustomizer类型的Bean,并依次调用WebServerFactoryCustomizer接口的customize方法做一些定制化。

java 复制代码
public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
    void customize(T factory);
}

2 创建、启动嵌入式Web容器

Spring的ApplicationContext,其抽象实现类AbstractApplicationContext#refresh

java 复制代码
protected void refresh(ApplicationContext applicationContext) {
  Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
  ((AbstractApplicationContext) applicationContext).refresh();
}

用来新建或刷新一个ApplicationContext,在refresh中会调用onRefresh,AbstractApplicationContext子类可重写onRefresh实现Context刷新逻辑。

ServletWebServerApplicationContext重写onRefresh以创建嵌入式Web容器:

java 复制代码
@Override
protected void onRefresh() {
  super.onRefresh();
  try {
    // 创建和启动Tomcat
    createWebServer();
  }
  catch (Throwable ex) {
    throw new ApplicationContextException("Unable to start web server", ex);
  }
}

createWebServer

java 复制代码
private void createWebServer() {
    // WebServer是Spring Boot抽象出来的接口,具体实现类就是不同Web容器
    WebServer webServer = this.webServer;
    ServletContext servletContext = this.getServletContext();
    
    // 若Web容器尚未创建
    if (webServer == null && servletContext == null) {
        // 通过Web容器工厂创建
        ServletWebServerFactory factory = this.getWebServerFactory();
        // 传入一个"SelfInitializer"
        this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
        
    } else if (servletContext != null) {
        try {
            this.getSelfInitializer().onStartup(servletContext);
        } catch (ServletException var4) {
          ...
        }
    }

    this.initPropertySources();
}

getWebServer

以Tomcat为例,主要调用Tomcat的API去创建各种组件:

java 复制代码
public WebServer getWebServer(ServletContextInitializer... initializers) {
    // 1.实例化一个Tomcat【Server组件】
    Tomcat tomcat = new Tomcat();
    
    // 2. 创建一个临时目录
    File baseDir = this.baseDirectory != null ? this.baseDirectory : this.createTempDir("tomcat");
    tomcat.setBaseDir(baseDir.getAbsolutePath());
    
    // 3.初始化各种组件
    Connector connector = new Connector(this.protocol);
    tomcat.getService().addConnector(connector);
    this.customizeConnector(connector);
    tomcat.setConnector(connector);
    tomcat.getHost().setAutoDeploy(false);
    this.configureEngine(tomcat.getEngine());
    
    // 4. 创建定制版的"Context"组件
    this.prepareContext(tomcat.getHost(), initializers);
    return this.getTomcatWebServer(tomcat);
}

prepareContext的Context指Tomcat的Context组件,为控制Context组件行为,Spring Boot自定义了TomcatEmbeddedContext类,继承Tomcat的StandardContext:

java 复制代码
public class TomcatEmbeddedContext extends StandardContext

3 注册Servlet

Q:有@RestController,为啥还自己去注册Servlet给Tomcat?

A:可能有些场景需注册你自定义的一个Servlet提供辅助功能,与主程序分开。

Q:SprongBoot不注册Servlet给Tomcat,直接用@Controller就能实现Servlet功能是为啥呢?

A:因为SprongBoot默认给我们注册了DispatcherSetvlet。

3.1 Servlet注解

SpringBoot启动类加@ServletComponentScan后,@WebServlet、@WebFilter、@WebListener标记的Servlet、Filter、Listener就可自动注册到Servlet容器:

java 复制代码
@SpringBootApplication
@ServletComponentScan   // 扫描同包下的 MyAuthFilter
public class DemoApplication { 
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

@WebFilter(filterName = "myAuth", urlPatterns = "/*")
public class MyAuthFilter implements Filter {
    @Autowired
    private TokenService tokenService; // 只能通过容器注入

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // ...
    }
}

在Web应用的入口类上加上@ServletComponentScan,并且在Servlet类上加上@WebServlet,这样Spring Boot会负责将Servlet注册到内嵌的Tomcat中。

3.2 ServletRegistrationBean

SpringBoot提供:

  • ServletRegistrationBean
  • FilterRegistrationBean
  • ServletListenerRegistrationBean

分别来注册Servlet、Filter、Listener。

如注册一个Servlet:

java 复制代码
// Spring框架中注册Servlet的常见方式,将自定义的Servlet映射到指定的URL路径
@Bean
public ServletRegistrationBean servletRegistrationBean() {
    return new ServletRegistrationBean(new HelloServlet(), "/hello");
}

返回一个ServletRegistrationBean,并将它当作Bean注册到Spring,因此你需要把这段代码放到Spring Boot自动扫描的目录中,或放到@Configuration标识的类中。

Spring会把这种类型的Bean收集起来,根据Bean里的定义向Tomcat注册Servlet。

3.3 动态注册

可创建一个类去实现ServletContextInitializer接口,并把它注册为一个Bean,Spring Boot会负责调用这个接口的onStartup。

实现ServletContextInitializer接口的类会被spring管理,而不是被Servlet容器管理。

java 复制代码
@Component
public class MyServletRegister implements ServletContextInitializer {

  	// 参数是ServletContext,可通过调其addServlet方法动态注册新的Servlet,这是Servlet 3.0后才有的功能
    @Override
    public void onStartup(ServletContext servletContext) {
    
        // Servlet 3.0规范新的API
        ServletRegistration myServlet = servletContext
                .addServlet("HelloServlet", HelloServlet.class);
                
        myServlet.addMapping("/hello");
        
        myServlet.setInitParameter("name", "Hello Servlet");
    }

}

ServletRegistrationBean也是通过ServletContextInitializer实现,实现ServletContextInitializer接口。

通过 ServletContextInitializer 接口可以向 Web 容器注册 Servlet,实现 ServletContextInitializer 接口的Bean被speing管理,但是在什么时机触发其onStartup()方法的呢? 通过 Tomcat 中的 ServletContainerInitializer 接口实现者,如TomcatStarter,创建tomcat时设置了该类,在tomcat启动时会触发ServletContainerInitializer实现者的onStartup()方法,在这个方法中触发ServletContextInitializer接口的onStartup()方法,如注册DispatcherServlet。

DispatcherServletRegistrationBean实现了ServletContextInitializer接口,它的作用就是向Tomcat注册DispatcherServlet,那它是在什么时候、如何被使用的呢? prepareContext方法调用了另一个私有方法configureContext,这个方法就包括了往Tomcat的Context添加ServletContainerInitializer对象:

java 复制代码
context.addServletContainerInitializer(starter, NO_CLASSES);

其中有DispatcherServletRegistrationBean。

4 定制Web容器

在Spring Boot中定制Web容器。如Spring Boot 2.0中可通过如下方式:

4.1 ConfigurableServletWebServerFactory

通用的Web容器工厂,定制Web容器通用参数:

java 复制代码
@Component
public class MyGeneralCustomizer implements
  WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.setPort(8081);
        factory.setContextPath("/hello");
     }
}

4.2 TomcatServletWebServerFactory

通过特定Web容器工厂进一步定制。

给Tomcat新增个V3alve,以向请求头里添加traceid,用于分布式追踪。

java 复制代码
class TraceValve extends ValveBase {
    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {

        request.getCoyoteRequest().getMimeHeaders().
        addValue("traceid").setString("1234xxxxabcd");

        Valve next = getNext();
        if (null == next) {
            return;
        }

        next.invoke(request, response);
    }

}

跟方式一类似,再添加一个定制器:

java 复制代码
@Component
public class MyTomcatCustomizer implements
        WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.setPort(8081);
        factory.setContextPath("/hello");
        factory.addEngineValves(new TraceValve() );

    }
}

本文由博客一文多发平台 OpenWrite 发布!

相关推荐
AGI杂货铺10 小时前
微软GraphRAG 端到端使用及自用工具类
python·microsoft·flask
云天徽上10 小时前
【数据可视化-108】2025年6月新能源汽车零售销量TOP10车企分析大屏(PyEcharts炫酷黑色主题可视化)
python·信息可视化·数据挖掘·数据分析·汽车·数据可视化·零售
站大爷IP10 小时前
Python元组:不可变但灵活的数据容器
python
IT北辰10 小时前
初学者也能懂!用Python做房屋销售数据分析,从0到1上手实战(附源码和数据)
开发语言·python·数据分析
蓝倾97610 小时前
1688拍立淘接口对接实战案例
java·开发语言·数据库·python·电商开放平台·开放api接口
站大爷IP10 小时前
Python列表:从入门到灵活运用的全攻略
python
言之。10 小时前
Django全局异常处理全攻略
python·django·sqlite
言之。10 小时前
Django REST Framework Serializer 进阶教程
python·django·sqlite
fyakm11 小时前
python和java爬虫优劣对比
java·爬虫·python