springboot 幾種屬性配置獲取

2021-10-18 04:58:55 字數 2718 閱讀 7978

整個專案結構:

1.通過 environment 去獲取屬性配置值

2.通過類註解@component 獲取類物件,再通過物件獲取屬性值,通過 @value("$") 給對應屬性賦值或者新增預設值

3.通過註解//@component @configurationproperties(prefix = "gerry.properties") 類來給對應屬性賦值

4.通過@configuration 建立註解,再方法中建立對應的物件方法

同級目錄properties檔案優先於yaml檔案屬性,-d設定優先 properties檔案

以下為原始碼:

public static void main(string args) ") 給對應屬性賦值或者新增預設值

* */

redisconfig redisconfig = context.getbean("redisconfig", redisconfig.class);

system.out.println("redis:"+redisconfig.getport()+" || "+redisconfig.gethost()+" || "+redisconfig.getauth());

/** 3.通過註解//@component @configurationproperties(prefix = "gerry.properties") 類來給對應屬性賦值

* * */

datasources datasources = context.getbean(datasources.class);

string s = datasources.tostring();

system.out.println("datasout:"+s);

/** 4.通過@configuration 建立註解,再方法中建立對應的物件方法

* */

datasourceconfig bean = context.getbean(datasourceconfig.class);

datasources datasources1 = bean.getdatasources();

system.out.println("username::"+datasources1.getusername()); }}

@component

public class user

public integer getid()

public void setid(integer id)

public string getname()

public void setname(string name)

public integer getage()

public void setage(integer age) }

@component

public class redisconfig ")

private int port;

@value("$")

private string host;

@value("$")

private string auth;

public int getport()

public void setport(int port)

public string gethost()

public void sethost(string host)

public string getauth()

public void setauth(string auth) }

//@component

//@configurationproperties(prefix = "gerry.properties")

public class datasources

public void setdriverclassname(string driverclassname)

public string getusername()

public void setusername(string username)

public string getpassword()

public void setpassword(string password)

public string geturl()

public void seturl(string url)

@override

public string tostring() ';

}} @configuration

public class datasourceconfig

}

local.ip.addr=192.168.1.110

redis.port = 6379

redis.host = 192.168.3.11

redis.auth = redis-01

gerry.properties.driverclassname = com.mysql.jdbc.driver

gerry.properties.username = wl

gerry.properties.password = 123456

gerry.properties.url = jdbc:mysql:///db

springboot 幾種屬性配置獲取

整個專案結構 1.通過 environment 去獲取屬性配置值 2.通過類註解 component 獲取類物件,再通過物件獲取屬性值,通過 value 給對應屬性賦值或者新增預設值 3.通過註解 component configurationproperties prefix gerry.prop...

Spring Boot中讀取配置屬性的幾種方式

value是比較常見的注入方式,功能強大但一般可讀性較差。value str private string str 注入普通字串 value private string hello 注入配置屬性 value private string systempropertiesname 注入作業系統屬性 ...

SpringBoot系列(四)資源檔案屬性配置

自定義資源檔案 1 首先在pom.xml中新增依賴,不新增的話讀取不到 org.springframework.boot spring boot configuration processor true 2 繫結資源檔案 configuration configurationproperties p...