Spring Boot 默認(rèn)不支持@PropertySource
讀取yaml 文件半抱,這也是Stackoverflow 上經(jīng)常給予的標(biāo)準(zhǔn)答案脓恕。
Spring 4.3 通過引入 PropertySourceFactory
接口使之成為可能。PropertySourceFactory
是PropertySource
的工廠類窿侈。默認(rèn)實(shí)現(xiàn)是 DefaultPropertySourceFactory
进肯,可以構(gòu)造ResourcePropertySource
實(shí)例。
可以通過普通的是實(shí)現(xiàn)構(gòu)造 createPropertySource棉磨, 需要做兩點(diǎn):
- 導(dǎo)入resource 到Properties 對(duì)象江掩。
- 構(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 注解有一個(gè) factory
屬性环形,通過這個(gè)屬性來注入 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抬吟,但是對(duì)于Spring 4.3 及其以上版本同樣適用萨咕。
翻譯拙劣,歡迎指正火本。
References
[Use @PropertySource with YAML files](
本文由 歧途老農(nóng) 創(chuàng)作危队,采用 CC BY 4.0 CN 協(xié)議 進(jìn)行許可。 可自由轉(zhuǎn)載钙畔、引用茫陆,但需署名作者且注明文章出處。如轉(zhuǎn)載至微信公眾號(hào)擎析,請(qǐng)?jiān)谖哪┨砑幼髡吖娞?hào)二維碼簿盅。