springboot讀取.properties配置文件中的map和list類型配置參數(shù)方式
更新時(shí)間:2025年03月25日 09:04:39 作者:碼靈
這篇文章主要介紹了springboot讀取.properties配置文件中的map和list類型配置參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
springboot讀取.properties配置文件中的map和list類型配置參數(shù)
xxx.properties文件中存放一組配置參數(shù),分別為map類型和list類型,做測(cè)試方式,讀取配置參數(shù)。
1.配置文件xxx.properties
#map 第一種方式 data.person.name=zhangsan data.person.sex=man data.person.age=11 data.person.url=xxxxxxxx #map 第二種方式 data.person[name]=zhangsan data.person[sex]=man data.person[age]=11 data.person[url]=xxxxxxxx #list 第一種方式 data.list[0]=apple0 data.list[1]=apple1 data.list[2]=apple2 #list 第二種方式 data.list=apple0,apple1,apple2
2.注入配置信息
@Configuration
@ConfigurationProperties(prefix = "data")
//如果只有一個(gè)主配置類文件,@PropertySource可以不寫
@PropertySource("classpath:xxx.properties")
public class PersonConfig {
/**
* data.person.name
* 這里map名需要和application.properties中的參數(shù)一致
*/
private Map<String, String> person = new HashMap<>();
/**
* data.list
* 這里list名需要和application.properties中的參數(shù)一致
*/
private List<String> list = new ArrayList<>();
/**
* 編寫get,set方法方便使用
*/
public Map<String, String> getPerson() {
return person;
}
public void setPerson(Map<String, String> person) {
this.person = person;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}3.使用
@Autowired
private PersonConfig personConfig;
@Test
public void contextLoads() {
Map<String, String> person = personConfig.getPerson();
List<String> list = personConfig.getList();
System.out.println("image:"+JSONObject.fromObject(person).toString());
System.out.println("list:"+ JSONArray.fromObject(list).toString());
}
//輸出結(jié)果
image:{"sex":"man","name":"zhangsan","age":"11","url":"xxxxxxxx"}
list:["apple0","apple1","apple2"]總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot實(shí)現(xiàn)JWT 認(rèn)證的項(xiàng)目實(shí)踐
本文介紹了Spring Boot中實(shí)現(xiàn)JWT認(rèn)證,并介紹了擴(kuò)展JWT認(rèn)證功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-08-08
分布式組件Gateway技術(shù)棧系統(tǒng)性理解和操作
這篇文章主要介紹了分布式組件Gateway技術(shù)棧系統(tǒng)性理解和操作,要真正理解和使用Gateway技術(shù)棧,需要從架構(gòu)認(rèn)知、核心機(jī)制、實(shí)踐應(yīng)用三個(gè)維度建立系統(tǒng)性理解,需要的朋友可以參考下2026-02-02
如何使用Spring?Boot設(shè)置上傳文件大小限制
上傳文件是互聯(lián)網(wǎng)中常應(yīng)用的場(chǎng)景之一,最典型的情況就是上傳頭像等,下面這篇文章主要給大家介紹了關(guān)于如何使用Spring?Boot設(shè)置上傳文件大小限制的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01

