SpringBoot實現(xiàn)加載yml文件中字典數(shù)據(jù)
將字典數(shù)據(jù),配置在 yml 文件中,通過加載yml將數(shù)據(jù)加載到 Map中
Spring Boot 中 yml 配置、引用其它 yml 中的配置。# 在配置文件目錄(如:resources)下新建application-xxx
必須以application開頭的yml文件, 多個文件用 "," 號分隔,不能換行
項目結構文件

application.yml
server:
port: 8088
application:
name: VipSoft Env Demo
spring:
profiles:
include:
dic # 在配置文件目錄(如:resources)下新建application-xxx 開頭的yml文件, 多個文件用 "," 號分隔,不能換行
#性別字典
user-gender:
0: 未知
1: 男
2: 女
application-dic.yml
將字典獨立到單獨的yml文件中
#支付方式 pay-type: 1: 微信支付 2: 貨到付款
在 resources 目錄下,創(chuàng)建META-INF目錄,創(chuàng)建 spring.factories文件,
Spring Factories是一種類似于Java SPI的機制,它在META-INF/spring.factories文件中配置接口的實現(xiàn)類名稱,然后在程序中讀取這些配置文件并實例化。
內容如下:
# Environment Post Processor org.springframework.boot.env.EnvironmentPostProcessor=com.vipsoft.web.utils.ConfigUtil
ConfigUtil
package com.vipsoft.web.utils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.util.Assert;
public class ConfigUtil implements EnvironmentPostProcessor {
private static Binder binder;
private static ConfigurableEnvironment environment;
public static String getString(String key) {
Assert.notNull(environment, "environment 還未初始化!");
return environment.getProperty(key, String.class, "");
}
public static <T> T bindProperties(String prefix, Class<T> clazz) {
Assert.notNull(prefix, "prefix 不能為空");
Assert.notNull(clazz, "class 不能為空");
BindResult<T> result = ConfigUtil.binder.bind(prefix, clazz);
return result.isBound() ? result.get() : null;
}
/**
* 通過 META-INF/spring.factories,觸發(fā)該方法的執(zhí)行,進行環(huán)境變量的加載
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (propertySource.getName().equals("refreshArgs")) {
return;
}
}
ConfigUtil.environment = environment;
ConfigUtil.binder = Binder.get(environment);
}
}
DictVo
package com.vipsoft.web.vo;
public class DictVO implements java.io.Serializable {
private static final long serialVersionUID = 379963436836338904L;
/**
* 字典類型
*/
private String type;
/**
* 字典編碼
*/
private String code;
/**
* 字典值
*/
private String value;
public DictVO(String code, String value) {
this.code = code;
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}DefaultController
package com.vipsoft.web.controller;
import com.vipsoft.web.utils.ConfigUtil;
import com.vipsoft.web.vo.DictVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@RestController
public class DefaultController {
@GetMapping(value = "/")
public String login() {
return "VipSoft Demo !!!";
}
@GetMapping("/list/{type}")
public List<DictVO> listDic(@PathVariable("type") String type) {
LinkedHashMap dict = ConfigUtil.bindProperties(type.replaceAll("_", "-"), LinkedHashMap.class);
List<DictVO> list = new ArrayList<>();
if (dict == null || dict.isEmpty()) {
return list;
}
dict.forEach((key, value) -> list.add(new DictVO(key.toString(), value.toString())));
return list;
}
}運行效果

單元測試
package com.vipsoft.web;
import com.vipsoft.web.controller.DefaultController;
import com.vipsoft.web.utils.ConfigUtil;
import com.vipsoft.web.vo.DictVO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class DicTest {
@Autowired
DefaultController defaultController;
@Test
public void DicListTest() throws Exception {
List<DictVO> pay_type = defaultController.listDic("pay-type");
pay_type.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue()));
List<DictVO> user_gender = defaultController.listDic("user-gender");
user_gender.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue()));
}
@Test
public void getString() throws Exception {
String includeYml = ConfigUtil.getString("spring.profiles.include");
System.out.println("application 引用了配置文件 =》 " + includeYml);
}
}
以上就是SpringBoot實現(xiàn)加載yml文件中字典數(shù)據(jù)的詳細內容,更多關于SpringBoot加載yml文件字典數(shù)據(jù)的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot整合Spring?Security過濾器鏈加載執(zhí)行流程源碼分析(最新推薦)
Spring?Boot?對于?Spring?Security?提供了自動化配置方案,可以使用更少的配置來使用?Spring?Security,這篇文章主要介紹了SpringBoot整合Spring?Security過濾器鏈加載執(zhí)行流程源碼分析,需要的朋友可以參考下2023-02-02
基于java SSM springboot實現(xiàn)抗疫物質信息管理系統(tǒng)
這篇文章主要介紹了基于JAVA SSM springboot實現(xiàn)的抗疫物質信息管理系統(tǒng),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08
使用ServletInputStream()輸入流讀取圖片方式
這篇文章主要介紹了使用ServletInputStream()輸入流讀取圖片方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
關于JSON.toJSONString()和Gson.toJson()方法的比較
本文介紹了兩種將Java對象轉換為JSON字符串的方法:阿里的`JSON.toJSONString()`和谷歌的`Gson.toJson()`,通過一個示例,展示了當使用繼承關系且子類覆蓋父類字段時,`Gson`會報錯,而`JSON`可以正常運行,作者建議在處理JSON相關操作時使用阿里的`JSON`類2024-11-11

