spring_reference/IX. ‘How-to’ guides/63.4. Use YAML for external...

24 lines
1.3 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.

### 63.4. 使用YAML配置外部属性
YAML是JSON的一个超集可以非常方便的将外部配置以层次结构形式存储起来。比如
```json
spring:
application:
name: cruncher
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/test
server:
port: 9000
```
创建一个application.yml文件将它放到classpath的根目录下并添加snakeyaml依赖Maven坐标为`org.yaml:snakeyaml`,如果你使用`spring-boot-starter`那就已经被包含了。一个YAML文件会被解析为一个Java `Map<String,Object>`和一个JSON对象类似Spring Boot会平伸该map这样它就只有1级深度并且有period-separated的keys跟人们在Java中经常使用的Properties文件非常类似。
上面的YAML示例对应于下面的application.properties文件
```java
spring.application.name=cruncher
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/test
server.port=9000
```
查看'Spring Boot特性'章节的[Section 23.6, “Using YAML instead of Properties”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-yaml)可以获取更多关于YAML的信息。