当前位置: 首页 > news >正文

Spring Boot如何启动嵌入式Tomcat?

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接口:

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。

public interface ServletWebServerFactory {WebServer getWebServer(ServletContextInitializer... initializers);
}

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

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方法做一些定制化。

public interface WebServerFactoryCustomizer<T extends WebServerFactory> {void customize(T factory);
}

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

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

protected void refresh(ApplicationContext applicationContext) {Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);((AbstractApplicationContext) applicationContext).refresh();
}

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

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

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

createWebServer

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去创建各种组件:

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:

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容器:

@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 {@Autowiredprivate TokenService tokenService; // 只能通过容器注入@Overridepublic 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:

// 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容器管理。
@Component
public class MyServletRegister implements ServletContextInitializer {// 参数是ServletContext,可通过调其addServlet方法动态注册新的Servlet,这是Servlet 3.0后才有的功能@Overridepublic void onStartup(ServletContext servletContext) {// Servlet 3.0规范新的APIServletRegistration 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对象:

context.addServletContainerInitializer(starter, NO_CLASSES);

其中有DispatcherServletRegistrationBean。

4 定制Web容器

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

4.1 ConfigurableServletWebServerFactory

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

@Component
public class MyGeneralCustomizer implementsWebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {public void customize(ConfigurableServletWebServerFactory factory) {factory.setPort(8081);factory.setContextPath("/hello");}
}

4.2 TomcatServletWebServerFactory

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

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

class TraceValve extends ValveBase {@Overridepublic 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);}}

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

 
@Component
public class MyTomcatCustomizer implementsWebServerFactoryCustomizer<TomcatServletWebServerFactory> {@Overridepublic void customize(TomcatServletWebServerFactory factory) {factory.setPort(8081);factory.setContextPath("/hello");factory.addEngineValves(new TraceValve() );}
}
http://www.wxhsa.cn/company.asp?id=240

相关文章:

  • sql随机查看数据
  • 自我介绍
  • 83、SpringMVC全局异常处理和数据校验
  • nginx反向代理
  • 微算法科技(NASDAQ: MLGO)基于阿基米德优化算法(AOA)的区块链存储优化方案
  • mysql常用命令
  • WebApi通用获取全量参数,不使用实体
  • 《【插件】2025版PS插件一键安装》
  • Nginx跨越设置
  • 依然是dots的介绍视频
  • 【GitHub每日速递】别再瞎买编程课了!这 2 个免费宝藏,从入门到职业规划全搞定
  • 你的项目一团糟-不是你的错-是框架的锅
  • 数据结构与算法-24.2-3查找树
  • 8 将GitHub远程仓库修改为ssh
  • Symfony学习笔记 - Symfony Documentation - Utilities(1)
  • IPv4向IPv6平滑过渡综合技术方案
  • TIA博图中的常用指令:定时器、计数器和触发器
  • Vue3项目开发专题精讲【左扬精讲】—— 企业网站系统(基于 Vue3 与 TypeScript 技术栈的企业网站系统开发实战)
  • Vue3项目开发专题精讲【左扬精讲】—— 商城网站系统(基于 Vue3 与 TypeScript 技术栈的企业网站系统开发实战)
  • $\LaTeX{}$之快速编译和删除中间文件 - Invinc
  • 我们一起“扒一扒”ReentrantLock:看看锁背后那些精妙的设计
  • win10使用openssl生成证书
  • $\LaTeX{}$之minted使用 - Invinc
  • linux服务器 系统服务文件
  • Codeforces Round 1049 (Div. 2) 部分题解
  • Critical Thinking Academic Writing
  • 1.3 课前问题思考
  • 【知识管理工具分享】基于AI搭建个人法律知识库:我的PandaWiki实践心得
  • 你的中间件一团糟-是时候修复它了-️
  • 超越-env-一份成熟的应用程序配置指南