24.6 Using YAML Instead of Properties

YAML是JSON的超集,因此,用于表达分层配置数据将是非常方便的.当SnakeYAML库在您的类路径中时,SpringApplication类自动支持YAML用于替代属性配置.

Note

如果你正在使用“Starters”,SnakeYAML依赖将自动由spring-boot-starter提供.

Loading YAML

Spring框架提供两个便捷类,可以用来加载YAML文档.YamlPropertiesFactoryBeanProperties方式加载YAML属性而YamlMapFactoryBeanmap方式加载YAML.

例如,考虑以下YAML文档

  1. environments:
  2. dev:
  3. url: http://dev.example.com
  4. name: Developer Setup
  5. prod:
  6. url: http://another.example.com
  7. name: My Cool App

前面的示例将转换为以下属性:

  1. environments.dev.url=http://dev.example.com
  2. environments.dev.name=Developer Setup
  3. environments.prod.url=http://another.example.com
  4. environments.prod.name=My Cool App

YAML列表表示为带[index]索引的属性键.例如,考虑以下YAML:

  1. my:
  2. servers:
  3. - dev.example.com
  4. - another.example.com

前面的例子将被转换为以下属性:

  1. my.servers[0]=dev.example.com
  2. my.servers[1]=another.example.com

为了使用Spring Boot Binder工具(其实是@ConfigurationProperties真正做的)像上述那样绑定属性,你的目标实例需要有一个类型为java.util.List(或者Set)的属性. 并且你还需要提供一个setter方法或者用变量来初始化它.例如,下面的例子演示了绑定前面所示的属性:

  1. @ConfigurationProperties(prefix="my")
  2. public class Config {
  3. private List<String> servers = new ArrayList<String>();
  4. public List<String> getServers() {
  5. return this.servers;
  6. }
  7. }

Exposing YAML as Properties in the Spring Environment

YamlPropertySourceLoader类可以用来暴露YAML为Spring环境中的PropertySource环境.这样做可以让你使用@Value注解占位符语法访问YAML属性.

Multi-profile YAML Documents

您可以配置多个特定配置YAML文档在一个单独的文件中,并通过使用spring.profiles键来指定程序采用哪个文档.如以下示例所示:

  1. server:
  2. address: 192.168.1.100
  3. ---
  4. spring:
  5. profiles: development
  6. server:
  7. address: 127.0.0.1
  8. ---
  9. spring:
  10. profiles: production
  11. server:
  12. address: 192.168.1.120

在前面的示例中,如果development配置激活,则server.address属性值为127.0.0.1.类似地,如果production配置激活,则server.address属性值为192.168.1.120. 如果developmentproduction配置都不激活,则属性值为192.168.1.100.

如果在应用程序上下文启动时没有显式配置激活,则会激活默认配置文件.在接下来的YAML中,我们为spring.security.user.password属性只在default profile中起作用:

  1. server:
  2.  port: 8000
  3. ---
  4. spring:
  5.  profiles: default
  6.  security:
  7.   user:
  8.    password: weak

然而,在下面的例子中,password属性总是设置,因为它不附加至任何配置文件中并且它必须在所有其他的配置中有必要时被显式的重置:

  1. server:
  2. port: 8000
  3. spring:
  4. security:
  5. user:
  6. password: weak

使用Spring.profiles指定的Spring特定配置文件可被使用!字符串任意的否定.如果在一个单一的文档中配置了否定和非否定配置,至少指定一个非否定的文件匹配,没有否定配置文件可能匹配.

YAML Shortcomings

YAML文件无法使用@PropertySource注解加载.所以,如果你需要加载YAML文件,您需要使用一个属性文件.