yaml是專門用來寫配置文件的語言。使用yaml來寫配置文件擴展性比較強而且十分方便。spring boot支持使用yaml語言來寫配置文件,使用snakeyaml庫來讀取配置文件。spring boot關於yaml詳細用法可以參考官方文檔。
下面列舉一些項目中常用的寫法,幫你快速入門。
1 寫yml文件的基本規則
a) 層級關系用縮進表示,相同的縮進表示的層級關系相同。
b) 縮進只能使用空格,不能使用tab鍵
例如在properties文件中有如下屬性:
spring. profiles.active=test
spring. jackson.default-property-inclusion=non_default
在yml文件要寫成這樣:
spring:
profiles:
active: test
jackson:
default-property-inclusion: non_default
2 支持數組類型,數組成員前面加 -
city:
- 北京
- 上海
- 深圳
- 南京
- 重慶
3 一個yml文件中可以寫多個配置文件,配置文件之間用 --分割
spring:
profiles:
active: test
--
spring:
profiles: prod
--
spring:
profiles: test
4 支持別名功能,可以先定義別名,再進行引用。使用& 定義別名,* 引用別名。
testDatabase: &testDatabase
username: test
password: test
driverClassName: com.mysql.jdbc.Driver
test-on-borrow: true
validation-query: SELECT 1
test:
datasource:
url: jdbc:mysql://10.50.10.100:3306/testdb?characterEncoding=utf-8
<<: *testDatabase
上面的代碼等同於
testDatabase: &testDatabase
username: test
password: test
driverClassName: com.mysql.jdbc.Driver
test-on-borrow: true
validation-query: SELECT 1
test:
datasource:
url: jdbc:mysql://10.50.10.100:3306/testdb?characterEncoding=utf-8
username: test
password: test
driverClassName: com.mysql.jdbc.Driver
test-on-borrow: true
validation-query: SELECT 1
別名功能在有重復配置的情況下特別有用,可以直接引用,避免寫重復的配置。項目中常常遇到要配置多個數據庫的情況,一般除了url,用戶名,密碼,其他的配置都是一樣的,利用別名就可以少寫重復的配置,也便於后面維護。
注意別名功能只能在同一個配置文件生效。例如如上面所示,在prod文件中定義的別名不能在test文件中被引用。
5 引用變量,引用變量使用${},也可以引用數組的值。可以先定義一下相同的值,在需要的地方直接引用即可。
spring:
profiles:
active: test
country: 中國
city:
- 北京
- 上海
- 深圳
- 南京
- 重慶
--
spring:
profiles: prod
myCountry: ${country}
myCity: ${city[0]}
--
spring:
profiles: test
myCountry: ${country}
myCity: ${city[1]}
6 寫長字符串,長字符串可以用"",在換行時使用 \
longStr: "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\
abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\
abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg"
作者:vasthua
鏈接:http://www.jianshu.com/p/e091df2ff1c4
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
