配置 Spring Boot Web 应用程序

更新于 2025-12-30

Eugen Paraschiv 2022-05-11

1. 概述

Spring Boot 功能强大;在本教程中,我们将介绍 Boot 中一些更有趣的配置选项。

2. 端口号

在主独立应用程序中,默认的 HTTP 端口是 8080;我们可以轻松地配置 Boot 使用不同的端口:

server.port=8083

对于基于 YAML 的配置:

server:
  port: 8083

也可以通过编程方式自定义服务器端口:

@Component
public class CustomizationBean implements
  WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactory container) {
        container.setPort(8083);
    }
}

3. 上下文路径(Context Path)

默认情况下,上下文路径为 “/”。如果这不符合需求,需要将其更改为类似 /app_name 的路径,可以通过以下方式快速简单地在属性文件中完成:

server.servlet.context-path=/springbootapp

对于基于 YAML 的配置:

server:
  servlet:
    context-path: /springbootapp

同样,也可以通过编程方式实现:

@Component
public class CustomizationBean
  implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactory container) {
        container.setContextPath("/springbootapp");
    }
}

4. 白标错误页(White Label Error Page)

如果你没有在配置中指定任何自定义实现,Spring Boot 会自动注册一个 BasicErrorController Bean。

当然,这个默认控制器也是可以配置的:

public class MyCustomErrorController implements ErrorController {
 
    private static final String PATH = "/error";
    
    @GetMapping(value = PATH)
    public String error() {
        return "Error haven";
    }
}

5. 自定义错误消息

Boot 默认提供 /error 映射,以合理的方式处理错误。

如果你想配置更具体的错误页面,Boot 提供了良好的支持,可通过统一的 Java DSL 来定制错误处理:

@Component
public class CustomizationBean
  implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
 
    @Override
    public void customize(ConfigurableServletWebServerFactory container) {        
        container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
        container.addErrorPages(new ErrorPage("/errorHaven"));
    }
}

这里我们特别将“Bad Request”(400 错误)映射到 /400 路径,其他所有错误则统一映射到 /errorHaven

一个非常简单的 /errorHaven 实现如下:

@GetMapping("/errorHaven")
String errorHeaven() {
    return "You have reached the haven of errors!!!";
}

输出结果:

You have reached the haven of errors!!!

6. 以编程方式关闭 Boot 应用程序

你可以借助 SpringApplication 以编程方式关闭 Boot 应用。它提供了一个静态方法 exit(),该方法接收两个参数:ApplicationContextExitCodeGenerator

@Autowired
public void shutDown(ExecutorServiceExitCodeGenerator exitCodeGenerator) {
    SpringApplication.exit(applicationContext, exitCodeGenerator);
}

通过这个工具方法,我们可以关闭应用程序。

7. 配置日志级别

你可以轻松调整 Boot 应用程序中的日志级别。从 1.2.0 版本开始,你可以在主属性文件中配置日志级别:

logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

与标准 Spring 应用一样,你也可以通过在类路径中添加自定义的 XML 或属性文件,并在 pom.xml 中引入相应的库(如 Logback、log4j、log4j2 等),来激活不同的日志系统。

8. 注册新的 Servlet

如果你使用内嵌服务器部署应用程序,可以通过在常规配置中将 Servlet 暴露为 Bean 来注册新的 Servlet:

@Bean
public HelloWorldServlet helloWorld() {
    return new HelloWorldServlet();
}

或者,也可以使用 ServletRegistrationBean

@Bean
public ServletRegistrationBean<SpringHelloWorldServlet> servletRegistrationBean() {
    ServletRegistrationBean<SpringHelloWorldServlet> bean =
      new ServletRegistrationBean<>(new SpringHelloWorldServlet(), "/springHelloWorld/*");
    bean.setLoadOnStartup(1);
    bean.addInitParameter("message", "SpringHelloWorldServlet special message");
    return bean;
}

9. 在 Boot 应用中配置 Jetty 或 Undertow

Spring Boot Starter 通常默认使用 Tomcat 作为内嵌服务器。如果需要更换,可以排除 Tomcat 依赖,并引入 Jetty 或 Undertow。

配置 Jetty

<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>
@Bean
public JettyServletWebServerFactory jettyEmbeddedServletContainerFactory() {
    JettyServletWebServerFactory jettyContainer = 
      new JettyServletWebServerFactory();
    
    jettyContainer.setPort(9000);
    jettyContainer.setContextPath("/springbootapp");
    return jettyContainer;
}

配置 Undertow

<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>
@Bean
public UndertowServletWebServerFactory embeddedServletContainerFactory() {
    UndertowServletWebServerFactory factory = 
      new UndertowServletWebServerFactory();
    
    factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {
        @Override
        public void customize(io.undertow.Undertow.Builder builder) {
            builder.addHttpListener(8080, "0.0.0.0");
        }
    });
    
    return factory;
}

10. 结论

在本文中,我们快速浏览了一些更有趣且实用的 Spring Boot 配置选项。

当然,在官方参考文档中还有更多配置和调优选项可供使用——以上只是我认为比较有用的一部分。