SpringBoot(5)、使用YAML代替Properties

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í)推送各種干貨:


qrcode_for_gh_577b64e73701_258.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容