Spring Boot @PropertySource 讀取 YAML 文件

Spring Boot 默認(rèn)不支持@PropertySource讀取yaml 文件,這也是Stackoverflow 上經(jīng)常給予的標(biāo)準(zhǔn)答案。

202005251716lDz7CR48

Spring 4.3 通過引入 PropertySourceFactory 接口使之成為可能。PropertySourceFactoryPropertySource 的工廠類。默認(rèn)實現(xiàn)是 DefaultPropertySourceFactory,可以構(gòu)造ResourcePropertySource 實例。

可以通過普通的是實現(xiàn)構(gòu)造 createPropertySource, 需要做兩點:

  • 導(dǎo)入resource 到Properties 對象。
  • 構(gòu)造 PropertySource 使用Properties。

具體例子:

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

注意:YAML 需要 SnakeYAML 1.18 或者更高版本。

@PropertySource 注解有一個 factory 屬性,通過這個屬性來注入 PropertySourceFactory,這里給出 YamlPropertySourceFactory的例子。

@SpringBootApplication
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yaml")
public class YamlPropertysourceApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx =
                SpringApplication.run(YamlPropertysourceApplication.class, args);

        ConfigurableEnvironment env = ctx.getEnvironment();
        env.getPropertySources()
                .forEach(ps -> System.out.println(ps.getName() + " : " + ps.getClass()));

        System.out.println("Value of `foo.bar` = " + env.getProperty("foo.bar"));
    }
}

注意:這里使用的是Spring Boot,但是對于Spring 4.3 及其以上版本同樣適用。

翻譯拙劣,歡迎指正。

References

[Use @PropertySource with YAML files](

本文由 歧途老農(nóng) 創(chuàng)作,采用 CC BY 4.0 CN 協(xié)議 進行許可。 可自由轉(zhuǎn)載、引用,但需署名作者且注明文章出處。如轉(zhuǎn)載至微信公眾號,請在文末添加作者公眾號二維碼。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容