Spring/SpringBoot中使用yaml/yml配置文件

Spring/SpringBoot中使用yaml/yml配置文件

需求

在使用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依赖有所不同

  1. yml
<dependency>
      <groupId>com.fasterxml.jackson.dataformat</groupId>
	    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
  1. yaml
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值