YAML是JSON的一个超集,可以非常方便地将外部配置以层次结构形式存储起来。当项目的类路径中有SnakeYAML库(springbootstarter中已经被包含)时,SpringApplication类将自动支持YAML作为properties的替代。
如果将项目中的application.properties文件修改为YAML文件(尾缀为.yml或yaml)的形式,则其配置信息就如同下面两个文件所示:
使用Properties:
-
- server.port=8081
- spring.datasource.driverClassName=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://121.196.166.2:3306/microservice
- spring.datasource.username=root
- spring.datasource.password=root
- #logging7
- logging.level.com.example.hellospringboot=debug
使用YAML:
- #DB configuration
- spring:
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- url: jdbc:mysql://localhost:3306/microservice
- username: root
- password: root
-
- #Logging
- logging:
- level:
- com.example.hellospringboot: debug
从上述配置文件中可以看出,yml文件是一个树状结构的配置,它与properties文件相比,有很大的不同,在编写时需要注意以下几点:
(1)在properties文件中是以“.”进行分割的,在yml中是用“:”进行分割的。
(2)yml的数据格式和json的格式很像,都是KV格式,并且通过“:”进行赋值。
(3)每个key的冒号后面一定都要加一个空格,例如driver-class-name后面的“:”之后,需要有一个空格,否则文件会报错。
由于在SpringBoot官方文档中,主要使用的是properties文件,而SpringCloud官网文档以及一些开源的项目中,大多数使用的是yml文件,这点一开始就要注意,由于Spring Cloud 用的比较多, 因此建议即使在Springboot 项目中,也推荐使用YAML格式,以便于代码风格一致。
另外,在使用IDEA编辑器时, 同时打开Spring Boot DevTools, 编辑YAML 文件的时候, 提示比较及时,按照提示选择的话,不仅输入量减少了,而且还不容易出错。