diff --git a/IV. Spring Boot features/23.6.1. Loading YAML.md b/IV. Spring Boot features/23.6.1. Loading YAML.md index e69de29..5c8c1e1 100644 --- a/IV. Spring Boot features/23.6.1. Loading YAML.md +++ b/IV. Spring Boot features/23.6.1. Loading YAML.md @@ -0,0 +1,43 @@ +### 23.6.1. 加载YAML + +Spring框架提供两个便利的类用于加载YAML文档,YamlPropertiesFactoryBean会将YAML作为Properties来加载,YamlMapFactoryBean会将YAML作为Map来加载。 + +示例: +```json +environments: + dev: + url: http://dev.bar.com + name: Developer Setup + prod: + url: http://foo.bar.com + name: My Cool App +``` +上面的YAML文档会被转化到下面的属性中: +```java +environments.dev.url=http://dev.bar.com +environments.dev.name=Developer Setup +environments.prod.url=http://foo.bar.com +environments.prod.name=My Cool App +``` +YAML列表被表示成使用[index]间接引用作为属性keys的形式,例如下面的YAML: +```json +my: + servers: + - dev.bar.com + - foo.bar.com +``` +将会转化到下面的属性中: +```java +my.servers[0]=dev.bar.com +my.servers[1]=foo.bar.com +``` +使用Spring DataBinder工具绑定那样的属性(这是@ConfigurationProperties做的事),你需要确定目标bean中有个java.util.List或Set类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定上面的属性: +```java +@ConfigurationProperties(prefix="my") +public class Config { + private List servers = new ArrayList(); + public List getServers() { + return this.servers; + } +} +```