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

202005251716lDz7CR48
Spring 4.3 通過引入 PropertySourceFactory 接口使之成為可能。PropertySourceFactory 是PropertySource 的工廠類。默認(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)載至微信公眾號,請在文末添加作者公眾號二維碼。