目录
SpringBoot加载指定YML文件
SpringBoot加载指定YML文件
Spring Boot默认支持properties和yml配置文件的读取,前者格式简单,但是只支持键值对。如果需要表达列表,最好使用YAML格式。
Spring Boot支持自动加载约定名称的配置文件,仅支持指定路径下指定名称的配置文件;例如application.yml。当自定义指定路径加载配置文件时,properties文件使用@PropertySource注解即可,但该注解并不支持加载yaml
老版本的SpringBoot可以通过@ConfigurationProperties的方式指定location;1.0.4之后该属性就取消了
@ConfigurationProperties(locations={"classpath:myconfig.yml"})
(1)YamlPropertiesFactoryBean:将yaml文件加载为Properties
@Configuration
public class YamlPropertyConfig {
/**
* 将yaml文件转为properties并设置到属性源
* @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;
}
}