4、SpringBoot嵌入式Servlet容器
文章目录
1、切换嵌入式Servlet容器
- 默认支持的web服务器webServer:
Tomcat, Jetty, Undertow
ServletWebServerApplicationContext 容器启动寻找ServletWebServerFactory 并引导创建服务器
切换服务器(可以切换四种)

切换的方式: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> 排除 <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> 导入 <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> 2022-07-17 19:34:02.650 INFO 6808 --- [ restartedMain] o.s.b.w.e.undertow.UndertowWebServer : Undertow started on port(s) 8080 (http)
原理
- SpringBoot应用启动发现当前是Web应用。因为导了web场景包,它里面也导入tomcat
- web应用会创建一个web版的ioc容器,名字叫
ServletWebServerApplicationContext ServletWebServerApplicationContext它在项目一启动的时候寻找ServletWebServerFactory(Servlet 的web服务器工厂---> 这个工厂生产 Servlet 的web服务器)- SpringBoot底层默认有很多的WebServer工厂:
TomcatServletWebServerFactory,JettyServletWebServerFactory,UndertowServletWebServerFactory - 这些web服务器工厂不需要我们配,底层直接会有一个自动配置类
ServletWebServerFactoryAutoConfiguration ServletWebServerFactoryAutoConfiguration导入了ServletWebServerFactoryConfiguration(配置类)ServletWebServerFactoryConfiguration配置类 根据动态判断系统中到底导入了哪个Web服务器的包。(默认是web-starter导入tomcat包),容器中就有TomcatServletWebServerFactoryTomcatServletWebServerFactory创建出Tomcat服务器TomcatWebServer并启动;TomcatWebServer 的构造器拥有初始化方法initialize,这个初始化方法把所有东西准备好,把tomcat调用start方法this.tomcat.start();启动tomcat- 其实内嵌服务器,就是手动把启动服务器的代码调用(前提是tomcat核心jar包存在,才能启动tomcat)
2、定制Servlet容器
- 实现 WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
○ 把配置文件的值和ServletWebServerFactory 进行绑定 - 修改配置文件 server.xxx
- 直接自定义 ConfigurableServletWebServerFactory
xxxxxCustomizer:定制化器,可以改变xxxx的默认规则
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory server) {
server.setPort(9000);
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论