SpringBoot默認支持properties和YAML兩種格式的配置文件。前者格式簡單,但是只支持鍵值對。如果需要表達列表,最好使用YAML格式。SpringBoot支持自動加載約定名稱的配置文件,例如application.yml
。如果是自定義名稱的配置文件,就要另找方法了。可惜的是,不像前者有@PropertySource
這樣方便的加載方式,后者的加載必須借助編碼邏輯來實現。
YamlPropertiesFactoryBean
SpringBoot文檔中給出了YamlPropertiesFactoryBean
和YamlMapFactoryBean
兩個類實現YAML配置文件的加載。前者將文件加載為Properties,后者為Map。
在網上搜到了這樣一個方法。
package com.example.demo.config;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
@Configuration
public class BootstrapConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("config/appprops.yml"));
propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
return propertySourcesPlaceholderConfigurer;
}
}
YamlPropertySourceLoader
文檔中還提到了YamlPropertySourceLoader
,但是沒有給出實現的代碼。今天看着API摸索了一下,找到了方案。
package com.example.demo.config;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
@Configuration
public class BootstrapConfig {
@Bean
public PropertySourcesPlaceholderConfigurer properties2() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
MutablePropertySources sources = new MutablePropertySources();
try {
sources.addLast(loader.load("db", new ClassPathResource("config/appprops.yml"), null));
} catch (IOException e) {
e.printStackTrace();
}
configurer.setPropertySources(sources);
return configurer;
}
}
簡單總結
前者不拋異常,看着更舒服;而后者可以支持同時加載多個YAML文件。