2015-02-08 14:06:15 +00:00
|
|
|
|
### 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<String> servers = new ArrayList<String>();
|
|
|
|
|
public List<String> getServers() {
|
|
|
|
|
return this.servers;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|