Spring Boot讀取配置的幾種方式

2022-09-07 15:36:25 字數 2479 閱讀 5825

info.address=usa\

info.company=spring\

info.degree=high

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)

}

@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

@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檔案讀取。

@component

@configurationproperties(prefix = "db")

@propertysource(value = )

public

class

dbconfig2

public

void

setusername(string username)

public string getpassword()

public

void

setpassword(string password)

}

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

@autowired

private environment env;

// 獲取引數

string getproperty(string key);

從以上示例來看,spring boot可以通過@propertysource,@value,@environment,@configurationproperties來繫結變數。

推薦閱讀

面經:史上最全j**a多執行緒面試題及答案

面經:史上最全阿里高階j**a面試題

面經:史上最全spring面試題

書籍:高階j**a架構師必看的15本書

SpringBoot讀取配置值的方式

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

Spring Boot讀取配置的幾種方式

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

spring boot 配置檔案讀取

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