YAML - Spring Boot 下更好的配置选择?
YAML an alternative to Properties file … with Spring Boot
对于许多Java工程师来说,一直习惯于使用properties文件或者xml文件来定义应用程序配置。但SpringBoot允许我们仅通过单个yml文件就可以完成所有与应用相关的配置。补充说明一下:比较不同格式的配置文件的优劣,都会有一定的主观性。但对于SpringBoot配置来说,依据官方文档的说法,使用YAML似乎只有一个缺点:使用通过注解PropertySource加载YAML文件。
YAML files can’t be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.
什么是YAML文件
It is a human friendly data serialization standard for all programming languages.
YAML是一种适用于所有编程语言的人性化数据序列化标准。YAML是JSON的子集,因而非常适用于定义树型配置参数。同时,YAML易于阅读,更利于工程师进行阅读和编辑。
YAML的设计目标
- 易于阅读
- 可移植性高,适用于各种编程语言
- 符合native data structures
- 包含一致性模型
- 支持one-pass处理
- 更好的语义表述性,易于扩展
- 易于实现,易于使用
使用YAML注意事项
你无法去校验YAML文件本身的完整性,相反,XML文件则总是要求格式完整。
YAML配置示例
environment:
profiles: dev
name: Developer App
url: http://dev.abc.com
profiles: qa
name: QA App
url: http://qa.abc.com
常见JAVA YAML解析器
- SnakeYAML
- JYaml
- YamlBeans
- JvYaml
Spring Boot使用SnakeYAML库加载解析YAML配置文件,YamlPropertiesFactoryBean将YAML文件解析为Properties文件,YamlMapFactoryBean将YAML文件解析为一个Map对象。
YamlPropertiesFactoryBean加载YAML文件方式
- 使用Java配置类
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("appConfig.yml");
propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
return propertySourcesPlaceholderConfigurer;
}
- 使用XML组件配置
<context:annotation-config/>
<bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
<property name="resources" value="classpath:appConfig.yml"/>
</bean>
<context:property-placeholder properties-ref="yamlProperties"/>