1. Server Substitute
Spring Boot自身支持Tomcat、Jetty、Undertow三种内置Server,默认Tomcat为内置服务器。可通过改变Maven dependency来替换Server。如要替换Tomcat为Jetty,maven pom部分代码如下:
<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-jetty</artifactId>
</dependency>
Server Configuration
Server配置可通过两种方式完成:
a、覆盖application.properties中以server作为prefix的属性的值来完成。
b、programming configuration,有两种形式。具体如下:
第一种形式:采用WebServerFactoryCustomizer接口访问ConfigurableServletWebServerFactory
package com.example.container;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class CustomServletContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>{
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.setPort(9009);
factory.setContextPath("/hello");
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
}
}
第二种形式:直接返回TomcatServletWebServerFactory等ServerFactory作为Bean
@Configuration
public class TomcatServletServerContainer {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory webServerFactory = new TomcatServletWebServerFactory();
webServerFactory.setPort(9010);
webServerFactory.setContextPath("/welcome");
webServerFactory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
return webServerFactory;
}
}
以上内容详见:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content
文中“27.4.4 Customizing Embedded Servlet Containers”节。