知識庫 / Spring / Spring Boot RSS 訂閱

使用YAML文件與Spring Boot的@PropertySource

Spring Boot
HongKong
5
12:56 PM · Dec 06 ,2025

1. 概述

本快速教程將演示如何使用 Spring Boot 中的 <span class="annotation">@PropertySource</span> 註解讀取 YAML 屬性文件。

2. @PropertySourceYAML 格式**

Spring Boot 對外部化配置提供了極佳的支持。 此外,Spring Boot 應用程序可以無縫地使用不同的方式和格式讀取屬性。

然而,默認情況下@PropertySource 不會自動加載 YAML 文件。這一事實在 官方文檔 中明確説明。

因此,如果我們要在應用程序中使用 @PropertySource 註解,則必須使用標準的 properties 文件。 或者,我們可以自己解決這個缺失的部分!

3. 自定義 PropertySourceFactory

從 Spring 4.3 版本開始,@PropertySource 提供了 工廠 屬性。我們可以利用它來提供我們自定義的 PropertySourceFactory 實現,該實現將處理 YAML 文件。

這比看起來要簡單得多! 讓我們看看如何做到這一點:

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) 
      throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(encodedResource.getResource());

        Properties properties = factory.getObject();

        return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
    }
}

如我們所見,只需實現一個 createPropertySource 方法即可。

在我們的自定義實現中,首先,我們使用 YamlPropertiesFactoryBean 將 YAML 格式的資源轉換為 java.util.Properties 對象。

然後,我們簡單地返回一個新的 PropertiesPropertySource 實例,該實例是一個包裝器,允許 Spring 讀取解析後的屬性。

4. @PropertySourceYAML 在實踐中的應用

現在,讓我們將所有組件整合起來,並瞭解如何在實踐中使用它們。

首先,讓我們創建一個簡單的 YAML 文件 – foo.yml

yaml:
  name: foo
  aliases:
    - abc
    - xyz

接下來,讓我們創建一個帶有 @ConfigurationProperties 的屬性類,並使用我們自定義的 YamlPropertySourceFactory

@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
public class YamlFooProperties {

    private String name;

    private List<String> aliases;

    // standard getter and setters
}

最後,讓我們驗證屬性是否正確注入:

@RunWith(SpringRunner.class)
@SpringBootTest
public class YamlFooPropertiesIntegrationTest {

    @Autowired
    private YamlFooProperties yamlFooProperties;

    @Test
    public void whenFactoryProvidedThenYamlPropertiesInjected() {
        assertThat(yamlFooProperties.getName()).isEqualTo("foo");
        assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz");
    }
}

5. 結論

總而言之,在本快速教程中,我們首先展示瞭如何輕鬆創建自定義的 <span title="PropertySourceFactory">PropertySourceFactory</span>。 隨後,我們演示瞭如何將此自定義實現傳遞到 <span title="@PropertySource">@PropertySource</span> 屬性中,利用其 <span title="factory">factory</span> 屬性。

因此,我們成功地將 YAML 屬性文件加載到我們的 Spring Boot 應用程序中。

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

發佈 評論

Some HTML is okay.