spring_reference/IV. Spring Boot features/23.6.1. Loading YAML.md

44 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 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;
}
}
```