需求
在使用Spring/SpringBoot的过程中,我们总会使用到各种自定义配置,不可能把所有的配置都写到application.yml中,此时我们可以将某一部分自定义配置单独用一个文件提取出来,Spring也提供了相应的解决方案。
例子
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();
};
}
}
结果
2018-12-06 17:06:32,312 INFO :-- [main .. ] o.s.SampleApplication 打印....
Email:test@163.com,Address:中华人民共和国
- 结语
此处提供的是基于Java注解的配置,在XML配置中把@Bean 注册的类改成XML注册的类便可。
- 补充
在项目中使用yml配置需要添加相关依赖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>