❶ 简介
❷ 默认 tomcat 服务器
➌ 查看内置服务器种类
❹ 类图
一、简介
Spring Boot支持的内嵌容器有Tomcat(默认)、Jetty、Undertow 和 Reactor
Netty(v2.0+),借助可插拔(SPI)机制的实现,开发者可以轻松进行容器间的切换。
如何切换成其它的嵌入式Servlet容器(Jetty 和 Undertow)
SpringBoot默认使用的内置Servlet容器是Tomcat,然而 SpringBoot还支持其它的Servlet容器 默认的Tomcat只是其中一种,SpringBoot还支持Jetty和Undertow;
二、默认 tomcat 服务器
当我们创建完 SpringBoot 项目导入web 依赖后,在启动后会发现默认启动的是 Tomcat 服务器,如下图空色框内所示:
三、查看内置服务器种类
查看路径:
org.springframework.boot.autoconfigure.web.embedded
查看源码,找到四种内置服务器。(在autoconfigure下的 web/embedded 下面),会发现如下图所示的四种服务器分别是Jetty、Netty、Tomcat、Undertow 服务器;还有一个配置服务器的条件类。
这里就是我们对应的 web 服务器工厂,jetty,netty,tomcat,undertow这四种,我们这里注意怎么切换这四种服务器即可
我们查看配置服务器的条件类 EmbeddedWebServerFactoryCustomizerAutoConfiguration 代码;
注意:Conditional 是条件判断,返回 boolean 值;如果为 true 才会执行该方法。
这里如果我们在程序中有相应的字节码文件的话,那么我们就会创建对应的服务器,这个 .class 是字节码文件
四、类图
从 pom 文件中 dependency 为 spring-boot-starter-web 中查看类图,可以看到 SpringBoot 默认内置服务器是 tomcat,所以我们想要使用其他服务器,只需要两步即可:
1⃣️必须先将 tomcat 服务器排除掉;
2⃣️然后再去进行依赖配置(pom 文件添加 dependency)要切换的服务器。
pom.xml 中添加依赖(这里以 jetty 服务器进行演示)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 排除 tomcat 依赖 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入 jetty 的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
启动看效果: