yaml是專門(mén)用來(lái)寫(xiě)配置文件的語(yǔ)言。使用yaml來(lái)寫(xiě)配置文件擴(kuò)展性比較強(qiáng)而且十分方便。spring boot支持使用yaml語(yǔ)言來(lái)寫(xiě)配置文件,使用snakeyaml庫(kù)來(lái)讀取配置文件。spring boot關(guān)于yaml詳細(xì)用法可以參考官方文檔。
下面列舉一些項(xiàng)目中常用的寫(xiě)法,幫你快速入門(mén)。
1 寫(xiě)yml文件的基本規(guī)則
a) 層級(jí)關(guān)系用縮進(jìn)表示,相同的縮進(jìn)表示的層級(jí)關(guān)系相同。
b) 縮進(jìn)只能使用空格,不能使用tab鍵
例如在properties文件中有如下屬性:
spring. profiles.active=test
spring. jackson.default-property-inclusion=non_default
在yml文件要寫(xiě)成這樣:
spring:
profiles:
active: test
jackson:
default-property-inclusion: non_default
2 支持?jǐn)?shù)組類(lèi)型,數(shù)組成員前面加 -
city:
- 北京
- 上海
- 深圳
- 南京
- 重慶
3 一個(gè)yml文件中可以寫(xiě)多個(gè)配置文件,配置文件之間用 --分割
spring:
profiles:
active: test
--
spring:
profiles: prod
--
spring:
profiles: test
4 支持別名功能,可以先定義別名,再進(jìn)行引用。使用& 定義別名,* 引用別名。
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
別名功能在有重復(fù)配置的情況下特別有用,可以直接引用,避免寫(xiě)重復(fù)的配置。項(xiàng)目中常常遇到要配置多個(gè)數(shù)據(jù)庫(kù)的情況,一般除了url,用戶名,密碼,其他的配置都是一樣的,利用別名就可以少寫(xiě)重復(fù)的配置,也便于后面維護(hù)。
注意別名功能只能在同一個(gè)配置文件生效。例如如上面所示,在prod文件中定義的別名不能在test文件中被引用。
5 引用變量,引用變量使用${},也可以引用數(shù)組的值。可以先定義一下相同的值,在需要的地方直接引用即可。
spring:
profiles:
active: test
country: 中國(guó)
city:
- 北京
- 上海
- 深圳
- 南京
- 重慶
--
spring:
profiles: prod
myCountry: ${country}
myCity: ${city[0]}
--
spring:
profiles: test
myCountry: ${country}
myCity: ${city[1]}
6 寫(xiě)長(zhǎng)字符串,長(zhǎng)字符串可以用"",在換行時(shí)使用 \
longStr: "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\
abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\
abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg"
參考文檔:
yaml語(yǔ)言教程