Spring Boot自动配置--如何切换内置Web服务器
简介
springboot的web环境默认使用Tomcat作为内置服务器,我们springboot其实提供了4种内置服务器供我们选择,我们可以很方便的进行切换。
分别是jetty,netty,tomcat,undertow这四种。
1.默认tomcat服务器
当我们创建完SpringBoot项目导入web依赖后,在启动后会发现默认启动的是Tomcat服务器,如下图空色框内所示:
2.查看内置服务器种类
查看源码,找到四种内置服务器。(在autoconfigure下的web/embedded下面),会发现如下图所示的四种服务器分别是Jetty、Netty、Tomcat、Undertow服务器。还有一个配置服务器的条件类。
这里就是我们对应的web服务器工厂,jetty,netty,tomcat,undertow这四种,我们这里注意怎么切换这四种服务器即可
我们查看配置服务器的条件类EmbeddedWebServerFactoryCustomizerAutoConfiguration代码。
注意:1.Conditional是条件判断,返回boolean值。如果为true才会执行该方法。
这里如果我们在程序中有相应的字节码文件的话,那么我们就会创建对应的服务器,这个.class是字节码文件
3.坐标
我们想要使用其他的服务器,我们要按照下面两个步骤即可
步骤:
1.必须现将Tomcat服务器排除掉
2.然后再去进行配置要切换的服务器。
pom.xml代码:
<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>
我们在pom.xml文件中引入对应坐标即可
效果展示: