YAML是JSON的一個(gè)超集,也是一種方便的定義層次配置數(shù)據(jù)的格式。無(wú)論你何時(shí)將YAML庫(kù)放到classpath下,SpringApplication類(lèi)都會(huì)自動(dòng)支持YAML作為properties的替換。
加載YAML
Spring框架提供兩個(gè)便利的類(lèi)用于加載YAML文檔:
1、YamlPropertiesFactoryBean會(huì)將YAML作為Properties來(lái)加載。
2、YamlMapFactoryBean會(huì)將YAML作為Map來(lái)加載。
例如一:
environments:
dev:
url: http://dev.ctw.com
name: Developer Setup
test:
url: http://test.ctw.com
name: Test Setup
provide
url: http://provide.ctw.com
name: Provide Setup
會(huì)轉(zhuǎn)變?yōu)椋?/p>
environments.dev.url=http://dev.ctw.com
environments.dev.name=Developer Setup
environments.test.url=http://test.ctw.com
environments.test.name=Test Setup
environments.provide.url=http://provide.ctw.com
environments.provide.name=Provide Setup
例如二、
YAML列表被表示成[index]間接引用作為屬性keys的形式。
my:
servers:
- dev.ctw.com
- test.ctw.com
- provide.ctw.com
會(huì)轉(zhuǎn)變?yōu)椋?/p>
my.servers[0]=dev.ctw.com
my.servers[1]=test.ctw.com
my.servers[2]=provide.ctw.com
使用Spring DataBinder工具綁定那樣的屬性(這是@ConfigurationProperties做的事),你需要確定目標(biāo)bean中有個(gè)List或Set類(lèi)型的屬性。并且需要提供一個(gè)setter或使用可變的值初始化他,比如下面的代碼綁定上面的屬性:
@ConfigurationProperties(prefix = "my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
多環(huán)境配置
server:
address: 192.168.0.100
---
spring:
profiles: dev
server:
address: 192.168.0.110
---
spring:
profiles: test
server:
address: 192.168.0.120
如果dev配置被激活,那么server.address屬性將是192.168.0.110,若dev和test都未被啟用,則屬性的值將是192.168.0.100。
若有興趣,歡迎來(lái)加入群,【Java初學(xué)者學(xué)習(xí)交流群】:458430385,此群有Java開(kāi)發(fā)人員、UI設(shè)計(jì)人員和前端工程師。有問(wèn)必答,共同探討學(xué)習(xí),一起進(jìn)步!
歡迎關(guān)注我的微信公眾號(hào)【Java碼農(nóng)社區(qū)】,會(huì)定時(shí)推送各種干貨:
