Java SpringBoot 加载 yml 配置文件中字典项

简介: Java SpringBoot 加载 yml 配置文件中字典项

实际项目中,如果将该类信息放配置文件中的话,一般会结合Nocas一起使用

将字典数据,配置在 yml 文件中,通过加载yml将数据加载到 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 目录下,创建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;
    }
}

运行效果

单元测试

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);
    }
}

目录
相关文章
|
9天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的服装商城管理系统
基于Java+Springboot+Vue开发的服装商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的服装商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
31 2
基于Java+Springboot+Vue开发的服装商城管理系统
|
6天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
基于Java+Springboot+Vue开发的大学竞赛报名管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的大学竞赛报名管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
20 3
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
|
7天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的蛋糕商城管理系统
基于Java+Springboot+Vue开发的蛋糕商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的蛋糕商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
20 3
基于Java+Springboot+Vue开发的蛋糕商城管理系统
|
7天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的美容预约管理系统
基于Java+Springboot+Vue开发的美容预约管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的美容预约管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
21 3
基于Java+Springboot+Vue开发的美容预约管理系统
|
9天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的房产销售管理系统
基于Java+Springboot+Vue开发的房产销售管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的房产销售管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
23 3
基于Java+Springboot+Vue开发的房产销售管理系统
|
10天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的反诈视频宣传系统
基于Java+Springboot+Vue开发的反诈视频宣传系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的反诈视频宣传管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
40 4
基于Java+Springboot+Vue开发的反诈视频宣传系统
|
9天前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的医院门诊预约挂号系统
基于Java+Springboot+Vue开发的医院门诊预约挂号系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的门诊预约挂号管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
31 2
基于Java+Springboot+Vue开发的医院门诊预约挂号系统
|
5天前
|
安全 Oracle Java
edge浏览器加载java插件
edge浏览器加载java插件
27 1
|
6天前
|
JSON NoSQL Java
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
这篇文章介绍了在Java中使用Redis客户端的几种方法,包括Jedis、SpringDataRedis和SpringBoot整合Redis的操作。文章详细解释了Jedis的基本使用步骤,Jedis连接池的创建和使用,以及在SpringBoot项目中如何配置和使用RedisTemplate和StringRedisTemplate。此外,还探讨了RedisTemplate序列化的两种实践方案,包括默认的JDK序列化和自定义的JSON序列化,以及StringRedisTemplate的使用,它要求键和值都必须是String类型。
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
|
8天前
|
消息中间件 NoSQL 安全
(转)Spring Boot加载 不同位置的 application.properties配置文件顺序规则
这篇文章介绍了Spring Boot加载配置文件的顺序规则,包括不同位置的application.properties文件的加载优先级,以及如何通过命令行参数或环境变量来指定配置文件的名称和位置。
下一篇
无影云桌面