知識庫 / Spring RSS 訂閱

Spring YAML 配置

Spring
HongKong
9
02:31 PM · Dec 06 ,2025

1. 概述

使用 YAML 配置文件配置 Spring 應用的一種方式是使用 YAML 配置文件。

在本快速教程中,我們將使用 YAML 配置不同環境(profiles)來配置一個簡單的 Spring Boot 應用程序。

2. Spring YAML 文件

Spring 配置文件有助於 Spring 應用定義針對不同環境的不同屬性。

讓我們來看一個包含兩個配置文件的簡單 YAML 文件。 三個短橫線分隔這兩個配置文件,表示一個新文檔的開始,因此所有配置文件都可以描述在同一個 YAML 文件中。

application.yml 文件的相對路徑為 /myApplication/src/main/resources/application.yml

spring:
    config:
        activate:
            on-profile: test
name: test-YAML
environment: testing
enabled: false
servers: 
    - www.abc.test.com
    - www.xyz.test.com

---
spring:
    config:
        activate:
            on-profile: prod
name: prod-YAML
environment: production
enabled: true
servers: 
    - www.abc.com
    - www.xyz.com

請注意,這種配置並不意味着這些配置文件在啓動應用程序時會生效。除非我們明確指示,否則配置文件中定義的屬性不會被加載;默認情況下,唯一活動的配置文件將是 ‘default.’。

3. 將 YAML 綁定到 Config 類

要從屬性文件加載一組相關屬性,我們將創建一個 Bean 類:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {
 
    private String name;
    private String environment;
    private boolean enabled;
    private List<String> servers = new ArrayList<>();

    // standard getters and setters

}

此處使用的註釋如下:

  • @Configuration此標記表明該類是 Bean 定義的來源
  • @ConfigurationProperties此標記將外部配置綁定到配置類,並進行驗證
  • @EnableConfigurationProperties此標記用於啓用 Spring 應用程序中帶有 @ConfigurationProperties 註解的 Bean

4. 訪問 YAML 屬性

要訪問 YAML 屬性,我們將創建一個 YAMLConfig 類的對象,並使用該對象訪問屬性。

在屬性文件中,我們將 spring.profiles.active 環境變量設置為 prod。 如果未定義此屬性,則只有 ‘default’ 配置文件處於活動狀態。

屬性文件的相對路徑為 /myApplication/src/main/resources/application.properties:

spring.profiles.active=prod

在此示例中,我們將使用 CommandLineRunner 來顯示屬性。

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    @Autowired
    private YAMLConfig myConfig;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run();
    }

    public void run(String... args) throws Exception {
        System.out.println("using environment: " + myConfig.getEnvironment());
        System.out.println("name: " + myConfig.getName());
        System.out.println("enabled:" + myConfig.isEnabled());
        System.out.println("servers: " + myConfig.getServers());
    }
}

命令行的輸出:

using environment: production
name: prod-YAML
enabled: true
servers: [www.abc.com, www.xyz.com]

5. YAML 屬性覆蓋在 Spring Boot 中,YAML 文件可以通過其他 YAML 屬性文件進行覆蓋。

在版本 2.4.0 之前,YAML 屬性通過以下位置的屬性文件進行覆蓋,優先級從高到低排列:

打包後的 Profile 屬性
  • 打包後的 Profile 屬性
  • 打包後的 Application 屬性
  • 打包後的 Application 屬性
  • 從 Spring Boot 2.4 版本開始,外部文件始終覆蓋打包文件,無論它們是否是 Profile 屬性,都有效。

    6. 結論

    在本文中,我們學習瞭如何使用 YAML 在 Spring Boot 應用程序中配置屬性。我們還討論了 Spring Boot 遵循的 YAML 文件屬性覆蓋規則。

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

    發佈 評論

    Some HTML is okay.