目錄
Spring Boot專欄目錄(點(diǎn)擊進(jìn)入…)
SpringBoot加載指定YML文件
Spring Boot默認(rèn)支持properties和yml配置文件的讀取,前者格式簡單,但是只支持鍵值對(duì)。如果需要表達(dá)列表,最好使用YAML格式。
Spring Boot支持自動(dòng)加載約定名稱的配置文件,僅支持指定路徑下指定名稱的配置文件;例如application.yml。當(dāng)自定義指定路徑加載配置文件時(shí),properties文件使用@PropertySource注解即可,但該注解并不支持加載yaml文章來源:http://www.zghlxwxcb.cn/news/detail-497706.html
老版本的SpringBoot可以通過@ConfigurationProperties的方式指定location;1.0.4之后該屬性就取消了文章來源地址http://www.zghlxwxcb.cn/news/detail-497706.html
@ConfigurationProperties(locations={"classpath:myconfig.yml"})
(1)YamlPropertiesFactoryBean:將yaml文件加載為Properties
@Configuration
public class YamlPropertyConfig {
/**
* 將yaml文件轉(zhuǎn)為properties并設(shè)置到屬性源
* @return
*/
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yamlProperties = new YamlPropertiesFactoryBean();
yamlProperties.setResources(new ClassPathResource("generator.yml"));
propertySourcesPlaceholderConfigurer.setProperties(yamlProperties.getObject());
return propertySourcesPlaceholderConfigurer;
}
}
(2)YamlPropertySourceLoader:將yaml文件加載為Map
@Configuration
public class YamlPropertyConfig {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer2() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
MutablePropertySources sources = new MutablePropertySources();
try {
List<PropertySource<?>> generator = loader.load("generator", new ClassPathResource("generator.yml"));
generator.stream().forEach(item -> {
sources.addLast(item);
});
} catch (IOException e) {
e.printStackTrace();
}
configurer.setPropertySources(sources);
return configurer;
}
}
到了這里,關(guān)于17.Spring Boot加載指定YML文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!