使用Spring從YAML文件讀取內(nèi)容映射為Map方式
從YAML文件讀取內(nèi)容映射為Map
如何在Spring Boot中從YAML文件注入到Map。
首先,將對Spring框架中的YAML文件有一些了解。 然后,通過一個(gè)實(shí)際示例展示如何將YAML屬性綁定到Map。
Spring框架中的YAML文件
使用YAML文件存儲(chǔ)外部配置數(shù)據(jù)是一種常見的做法。 基本上,Spring支持使用YAML文檔作為屬性的替代方法,并在后臺(tái)使用SnakeYAML對其進(jìn)行解析。
看看典型的YAML文件是什么樣的:
server: ? port: 8090 ? application: ? ? name: myapplication ? ? url: http://myapplication.com
從上面可以看出,YAML文件是不言自明的,更易于閱讀。 實(shí)際上,YAML提供了一種簡潔的方式來存儲(chǔ)分層配置數(shù)據(jù)。
默認(rèn)情況下,Spring Boot在應(yīng)用程序啟動(dòng)時(shí)從application.properties或application.yml讀取配置屬性。 但是,我們可以使用@PropertySource加載自定義的YAML文件。
既然熟悉了什么是YAML文件,看看如何在Spring Boot中將YAML屬性作為Map注入。
從YAML文件內(nèi)容注入Map
Spring Boot通過提供一個(gè)方便的注解@ConfigurationProperties,將數(shù)據(jù)的外部化提升到了一個(gè)新的水平。 引入此注解是為了輕松地將配置文件中的外部屬性直接注入Java對象。
接下來將介紹如何使用@ConfigurationProperties注解將YAML屬性綁定到bean類中。
首先,在application.yml中定義一些鍵值屬性:
server: ? application: ? ? name: InjectMapFromYAML ? ? url: http://injectmapfromyaml.dev ? ? description: How To Inject a map from a YAML File in Spring Boot ? config: ? ? ips: ? ? ? - 10.10.10.10 ? ? ? - 10.10.10.11 ? ? ? - 10.10.10.12 ? ? ? - 10.10.10.13 ? ? filesystem: ? ? ? - /dev/root ? ? ? - /dev/md2 ? ? ? - /dev/md4 ? users:? ? ? root: ? ? ? username: root ? ? ? password: rootpass ? ? guest: ? ? ? username: guest ? ? ? password: guestpass
其次,創(chuàng)建一個(gè)bean類MapServerProperties來封裝將配置屬性綁定到Maps的邏輯:
@Configuration
@ConfigurationProperties(prefix = "server")
@Data
public class MapServerProperties {
? ? private Map<String, String> application;
? ? private Map<String, List<String>> config;
? ? private Map<String, Credential> users;
? ? @Data
? ? public static class Credential {
? ? ? ? private String username;
? ? ? ? private String password;
? ? }
}如上面所見,我們用@ConfigurationProperties裝飾了MapServerProperties類。 這樣,告訴Spring將具有指定前綴的所有屬性映射到MapServerProperties的對象。
測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapFromYamlIntegrationTest {
? ? @Autowired
? ? private MapServerProperties mapServerProperties;
? ? @Test
? ? public void whenYamlFileProvidedThenInjectSimpleMap() {
? ? ? ? assertThat(mapServerProperties.getApplication())
? ? ? ? ? ? ? ? .containsOnlyKeys("name", "url", "description");
? ? ? ? assertThat(mapServerProperties.getApplication()
? ? ? ? ? ? ? ? .get("name")).isEqualTo("InjectMapFromYAML");
? ? }
? ? @Test
? ? public void whenYamlFileProvidedThenInjectComplexMap() {
? ? ? ? assertThat(mapServerProperties.getConfig()).hasSize(2);
? ? ? ? assertThat(mapServerProperties.getConfig()
? ? ? ? ? ? ? ? .get("ips")
? ? ? ? ? ? ? ? .get(0)).isEqualTo("10.10.10.10");
? ? ? ? assertThat(mapServerProperties.getUsers()
? ? ? ? ? ? ? ? .get("root")
? ? ? ? ? ? ? ? .getUsername()).isEqualTo("root");
? ? }
}@ConfigurationProperties與@Value
快速比較@ConfigurationProperties和@Value。
盡管兩個(gè)注解均可用于從配置文件注入屬性,但它們卻大不相同。 這兩個(gè)注釋之間的主要區(qū)別在于,每個(gè)注釋具有不同的用途。
簡而言之,@Value允許我們通過鍵直接注入特定的屬性值。 但是,@ConfigurationProperties批注將多個(gè)屬性綁定到特定對象,并提供通過映射對象對屬性的訪問。
通常,在注入配置數(shù)據(jù)時(shí),Spring建議在@Value上使用@ConfigurationProperties。 @ConfigurationProperties提供了一種在結(jié)構(gòu)化對象中集中和分組配置屬性的好方法,以后我們可以將其注入其他bean。
配置文件yml中的map形式
yml中的格式
tes:
maps: {key1: 12,key2: 34}或者
tes:
maps:
key1: 15
key2: 2創(chuàng)建一個(gè)類
然后創(chuàng)建對應(yīng)類型的字段(注意下這個(gè)類的那兩個(gè)注釋了的注解)
package com.etc.lzg;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Map;
@Data
@Component
//@Configuration //這個(gè)我這里雖然存在時(shí)能成功,不過我注釋了也是可以的,這個(gè)是看網(wǎng)上有人寫就跟著寫上的
//@PropertySource(value = {"classpath:/application.yml"}, encoding = "utf-8") //有的人是寫了這個(gè)注解能成功,但是我這邊不能有這個(gè)注解,有的話,就連編譯都會(huì)報(bào)錯(cuò)
@ConfigurationProperties(prefix = "tes")
public class MapTest {
private Map<String, String> maps;
}引用
package com.etc.lzg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LzgApplicationTests {
@Autowired
private MapTest mapTest;
@Test
public void contextLoads() {
System.out.println(mapTest.toString());
System.out.println("key1="+mapTest.getMaps().get("key1"));
}
}打印

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot中的maven插件spring-boot-maven-plugin使用
這篇文章主要介紹了SpringBoot中的maven插件spring-boot-maven-plugin使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
spring boot 即時(shí)重新啟動(dòng)(熱更替)使用說明
這篇文章主要介紹了spring boot 即時(shí)重新啟動(dòng)(熱更替)的相關(guān)資料,需要的朋友可以參考下2017-12-12
Java中將接口返回的字節(jié)串轉(zhuǎn)為文件詳解
這篇文章主要給大家介紹了關(guān)于Java中將接口返回的字節(jié)串轉(zhuǎn)為文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-11-11
教你1秒將本地SpringBoot項(xiàng)目jar包部署到Linux環(huán)境(超詳細(xì)!)
spring Boot簡化了Spring應(yīng)用的開發(fā)過程,遵循約定優(yōu)先配置的原則提供了各類開箱即用(out-of-the-box)的框架配置,下面這篇文章主要給大家介紹了關(guān)于1秒將本地SpringBoot項(xiàng)目jar包部署到Linux環(huán)境的相關(guān)資料,超級(jí)詳細(xì),需要的朋友可以參考下2023-04-04
Spring JPA聯(lián)表查詢之OneToMany源碼解析
這篇文章主要為大家介紹了Spring JPA聯(lián)表查詢之OneToMany源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

