24.6 Using YAML Instead of Properties
YAML是JSON的超集,因此,用于表达分层配置数据将是非常方便的.当SnakeYAML库在您的类路径中时,SpringApplication
类自动支持YAML用于替代属性配置.
Note
如果你正在使用“Starters”,SnakeYAML依赖将自动由
spring-boot-starter
提供.
Loading YAML
Spring框架提供两个便捷类,可以用来加载YAML文档.YamlPropertiesFactoryBean
以Properties
方式加载YAML属性而YamlMapFactoryBean
以map
方式加载YAML.
例如,考虑以下YAML文档
environments:
dev:
url: http://dev.example.com
name: Developer Setup
prod:
url: http://another.example.com
name: My Cool App
前面的示例将转换为以下属性:
environments.dev.url=http://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=http://another.example.com
environments.prod.name=My Cool App
YAML列表表示为带[index]索引的属性键.例如,考虑以下YAML:
my:
servers:
- dev.example.com
- another.example.com
前面的例子将被转换为以下属性:
my.servers[0]=dev.example.com
my.servers[1]=another.example.com
为了使用Spring Boot Binder工具(其实是@ConfigurationProperties真正做的)像上述那样绑定属性,你的目标实例需要有一个类型为java.util.List(或者Set)的属性. 并且你还需要提供一个setter方法或者用变量来初始化它.例如,下面的例子演示了绑定前面所示的属性:
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
Exposing YAML as Properties in the Spring Environment
YamlPropertySourceLoader
类可以用来暴露YAML为Spring环境中的PropertySource
环境.这样做可以让你使用@Value注解占位符语法访问YAML属性.
Multi-profile YAML Documents
您可以配置多个特定配置YAML文档在一个单独的文件中,并通过使用spring.profiles键来指定程序采用哪个文档.如以下示例所示:
server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production
server:
address: 192.168.1.120
在前面的示例中,如果development
配置激活,则server.address
属性值为127.0.0.1
.类似地,如果production
配置激活,则server.address
属性值为192.168.1.120
.
如果development
和production
配置都不激活,则属性值为192.168.1.100
.
如果在应用程序上下文启动时没有显式配置激活,则会激活默认配置文件.在接下来的YAML中,我们为spring.security.user.password
属性只在default profile
中起作用:
server:
port: 8000
---
spring:
profiles: default
security:
user:
password: weak
然而,在下面的例子中,password属性总是设置,因为它不附加至任何配置文件中并且它必须在所有其他的配置中有必要时被显式的重置:
server:
port: 8000
spring:
security:
user:
password: weak
使用Spring.profiles指定的Spring特定配置文件可被使用!字符串任意的否定.如果在一个单一的文档中配置了否定和非否定配置,至少指定一个非否定的文件匹配,没有否定配置文件可能匹配.
YAML Shortcomings
YAML文件无法使用@PropertySource注解加载.所以,如果你需要加载YAML文件,您需要使用一个属性文件.