需求
在使用Spring/SpringBoot的過程中,我們總會(huì)使用到各種自定義配置,不可能把所有的配置都寫到application.yml中,此時(shí)我們可以將某一部分自定義配置單獨(dú)用一個(gè)文件提取出來,Spring也提供了相應(yīng)的解決方案。
例子
test.yml
huaiku:
email: test@163.com
address: 中華人民共和國
使用
public class YmlConfigTestBean {
private String email;
private String address;
public YmlConfigTestBean(String email,String address) {
this.address = address;
this.email = email;
}
public void print() {
System.out.println(String.format("Email:%s,Address:%s", this.email,this.address));
}
}
配置
@Configuration
public class ApplicationConfigurations {
@Bean public PropertyPlaceholderConfigurer yamlPropertyPlaceholderBean() {
// 解析 yaml
YamlPropertiesFactoryBean yamlProperty = new YamlPropertiesFactoryBean();
yamlProperty.setResources(new ClassPathResource("test.yml"));
// 配置 PropertyPlaceholder
PropertyPlaceholderConfigurer yamlPropertyPlaceholder = new PropertyPlaceholderConfigurer();
yamlPropertyPlaceholder.setProperties(yamlProperty.getObject());
yamlPropertyPlaceholder.setFileEncoding("UTF-8");
return yamlPropertyPlaceholder;
}
@Bean public YmlConfigTestBean ymlConfigTestBean(@Value("${huaiku.email}")String email,@Value("${huaiku.address}")String address) {
return new YmlConfigTestBean(email,address);
}
}
測試
@SpringBootApplication
public class SampleApplication {
private static final Logger logger = LoggerFactory.getLogger(SampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
@Bean public CommandLineRunner test(final YmlConfigTestBean bean) {
return (args)-> {
logger.info("打印....");
bean.print();
};
}
}
結(jié)果
2018-12-06 17:06:32,312 INFO :-- [main .. ] o.s.SampleApplication 打印....
Email:test@163.com,Address:中華人民共和國
- 結(jié)語
此處提供的是基于Java注解的配置,在XML配置中把@Bean 注冊(cè)的類改成XML注冊(cè)的類便可。
- 補(bǔ)充
在項(xiàng)目中使用yml配置需要添加相關(guān)依賴yaml和yml依賴有所不同
- yml
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> </dependency>
- yaml
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>