知識庫 / Spring / Spring Boot RSS 訂閱

配置 Spring Boot Web 應用

Spring Boot
HongKong
6
02:53 PM · Dec 06 ,2025

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. 上下文路徑

默認情況下,上下文路徑為“/”。如果這不理想,並且您需要將其更改為例如“/app_name” ,則可以通過屬性文件以快速簡單的方式進行更改:

server.servlet.contextPath=/springbootapp

對於基於 YAML 的配置:

server:
    servlet:
        contextPath:/springbootapp

終於——更改也可以通過編程方式進行:

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

4. 白色標籤錯誤頁面

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 映射,以合理的方式處理錯誤。

如果您想配置更具體的錯誤頁面,則對錯誤處理有良好的統一 Java DSL 支持:

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

在此,我們專門處理了 Bad Request 請求,以匹配 /400 路徑,以及所有其他請求以匹配通用的路徑。

以及一個非常簡單的 /errorHaven 實現:

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

輸出:

You have reached the haven of errors!!!

6. 編程方式關閉啓動應用程序

您可以使用 SpringApplication 編程方式關閉 Boot 應用程序。它具有一個靜態 exit() 方法,該方法接受兩個參數: ApplicationContext 和一個 ExitCodeGenerator

@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 或 properties 文件,並在 pom 中定義庫來激活不同的日誌系統,例如 Logback, log4j, log4j2, 等等。

8. 註冊新的 Servlet

如果您使用嵌入式服務器部署應用程序,可以通過將它們暴露為從常規配置中定義的Bean來在 Boot 應用程序中註冊新的 Servlet。

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

當然,以下是翻譯後的內容:

或者,您可以使用 ServletRegistrationBean

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

9. 配置 Boot 應用程序中的 Jetty 或 Undertow

Spring Boot 啓動器通常使用 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 JettyEmbeddedServletContainerFactory  jettyEmbeddedServletContainerFactory() {
    JettyEmbeddedServletContainerFactory jettyContainer = 
      new JettyEmbeddedServletContainerFactory();
    
    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 UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
    UndertowEmbeddedServletContainerFactory factory = 
      new UndertowEmbeddedServletContainerFactory();
    
    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 配置選項

當然,還有許多其他選項可用於配置和調整 Boot 應用以滿足您的需求,這些選項可以在參考文檔中找到。這些只是我個人認為最有用的部分。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.