
SpringBoot提供了内置的web服务器,包括Tomcat、Jetty和Undertow等。它们都是通过SpringBoot的自动配置来实现的。
当我们在pom.xml文件中引入SpringBoot的web依赖时,会自动引入嵌入式web服务器依赖,如下所示:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>在启动应用程序时,SpringBoot会检测当前classpath下的嵌入式web服务器,并根据情况选择其中一个来作为应用程序的web服务器,并自动配置相关的参数。
例如,如果classpath下同时存在Tomcat、Jetty和Undertow,SpringBoot会默认选择Tomcat作为嵌入式web服务器。当然,我们也可以通过配置文件来显式指定使用哪个服务器。
在SpringBoot的自动配置中,还会根据应用程序的需求自动配置web服务器的行为,包括默认的请求处理器、错误页面、静态资源处理等等。我们只需要按照SpringBoot的要求来编写代码,即可快速开发出基于嵌入式web服务器的应用程序。
查看继承关系图

排除Tomcat

pom文件中的排除依赖效果
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--排除tomcat依赖-->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入jetty的依赖-->
<dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>SpringBoot支持多种内置的Web服务器,包括Tomcat、Undertow和Jetty。你可以通过修改pom.xml文件或配置文件来切换内置的Web服务器。
Tomcat是SpringBoot默认的内置Web服务器。如果你希望切换到Tomcat,则无需额外配置。
如果你希望切换到Undertow,则需要在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>如果你希望切换到Jetty,则需要在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>完成依赖修改后,在配置文件中添加以下配置即可:
server:
port: 8080
jetty:
acceptors: 2
selectors: 2我们将Jetty配置为使用2个接收器和2个选择器。
注意:无论使用哪种内置Web服务器,SpringBoot都会自动配置其性能特征,以充分利用服务器的能力。因此,你无需手动对Web服务器进行配置。