首頁 Java java教程 SpringBoot怎麼實作載入yml檔中字典數據

SpringBoot怎麼實作載入yml檔中字典數據

May 11, 2023 am 09:34 AM
springboot yml

將字典數據,配置在 yml 檔案中,透過載入yml將資料載入到 Map中

Spring Boot 中 yml 配置、引用其它 yml 中的配置。 # 在設定檔目錄(如:resources)下新建application-xxx

必須以application開頭的yml文件, 多個檔案以"," 號分隔,不能換行

專案結構檔

SpringBoot怎麼實作載入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 目錄下,建立META-INF目錄,建立 spring.factories文件,

Spring Factories是一種類似Java SPI的機制,它在META-INF/spring.factories檔案中配置介面的實作類別名稱,然後在程式中讀取這些設定檔並實例化。

內容如下:

# 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,触发该方法的执行,进行环境变量的加载
    */
    @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;
    }
}
登入後複製

運行效果

SpringBoot怎麼實作載入yml檔中字典數據

單元測試

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怎麼實作載入yml檔中字典數據#

以上是SpringBoot怎麼實作載入yml檔中字典數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Springboot怎麼整合Jasypt實現設定檔加密 Springboot怎麼整合Jasypt實現設定檔加密 Jun 01, 2023 am 08:55 AM

Springboot怎麼整合Jasypt實現設定檔加密

怎麼在SpringBoot中使用Redis實現分散式鎖 怎麼在SpringBoot中使用Redis實現分散式鎖 Jun 03, 2023 am 08:16 AM

怎麼在SpringBoot中使用Redis實現分散式鎖

SpringBoot怎麼整合Redisson實現延遲隊列 SpringBoot怎麼整合Redisson實現延遲隊列 May 30, 2023 pm 02:40 PM

SpringBoot怎麼整合Redisson實現延遲隊列

SpringBoot與SpringMVC的比較及差別分析 SpringBoot與SpringMVC的比較及差別分析 Dec 29, 2023 am 11:02 AM

SpringBoot與SpringMVC的比較及差別分析

springboot讀取檔案打成jar包後存取不到怎麼解決 springboot讀取檔案打成jar包後存取不到怎麼解決 Jun 03, 2023 pm 04:38 PM

springboot讀取檔案打成jar包後存取不到怎麼解決

SpringBoot怎麼自訂Redis實作快取序列化 SpringBoot怎麼自訂Redis實作快取序列化 Jun 03, 2023 am 11:32 AM

SpringBoot怎麼自訂Redis實作快取序列化

Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Jun 02, 2023 am 11:07 AM

Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現

springboot怎麼取得application.yml裡值 springboot怎麼取得application.yml裡值 Jun 03, 2023 pm 06:43 PM

springboot怎麼取得application.yml裡值

See all articles