Spring Boot讀取配置的幾種方式

2021-10-04 01:21:10 字數 2306 閱讀 3343

當大家看到這篇部落格的時候 ,相信已經對springboot有了簡單的了解。也看過很多人的demo,但是會發現 不同的程式設計師 在獲取配置資訊時 使用的方式不一樣,不免會搞得一頭霧水,下面我們來一起看一下 具體有哪些方式。

info.address=usa

info.company=spring

info.degree=high

@value註解讀取方式

import org.springframework.beans.factory.annotation.value;

import org.springframework.stereotype.component;

@component

public class infoconfig1 "

) private string address;

@value(

"$")

private string company;

@value(

"$")

private string degree;

public string getaddress()

public void setaddress(string address)

public string getcompany()

public void setcompany(string company)

public string getdegree()

public void setdegree(string degree)

}

@configurationproperties註解讀取方式

@component

@configurationproperties(prefix =

"info"

)public class infoconfig2

public void setaddress(string address)

public string getcompany()

public void setcompany(string company)

public string getdegree()

public void setdegree(string degree)

}

資源目錄下建立config/db-config.properties:
db.username=root

db.password=123456

2.1@propertysource+@value註解讀取方式

@component

@propertysource(value =

)public class dbconfig1 "

) private string username;

@value(

"$")

private string password;

public string getusername()

public void setusername(string username)

public string getpassword()

public void setpassword(string password)

}

注意:@propertysource不支援yml檔案讀取。

2.2@propertysource+@configurationproperties註解讀取方式

@component

@configurationproperties(prefix =

"db"

)@propertysource(value =

)public class dbconfig2

public void setusername(string username)

public string getpassword()

public void setpassword(string password)

}

3.environment讀取方式

以上所有載入出來的配置都可以通過environment注入獲取到。

@autowired

private environment env;

// 獲取引數

string getproperty(string key)

;

SpringBoot讀取配置值的方式

value註解的方式取值 xiaoming.boy xiaoming.age 18 xiaoming.score 98使用 value取值 restcontroller public class personcontroller private string value private intege...

Spring Boot讀取配置的幾種方式

info.address usa info.company spring info.degree high import org.springframework.beans.factory.annotation.value import org.springframework.stereotype....

spring boot 配置檔案讀取

如圖所示,可以重新賦值予以覆蓋。mail setting 設定郵箱主機 email.host smtp.163.com email.port 25 設定使用者名稱 email.from xx xx.com 設定密碼 email.frompassword 設定是否需要認證,如果為true,那麼使用者名...