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
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
这篇文章详细介绍了如何在前端Vue项目和后端Spring Boot项目中通过多种方式解决跨域问题。
178 1
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
|
4天前
|
JavaScript Java 关系型数据库
自主版权的Java诊所管理系统源码,采用Vue 2、Spring Boot等技术栈,支持二次开发
这是一个自主版权的Java诊所管理系统源码,支持二次开发。采用Vue 2、Spring Boot等技术栈,涵盖患者管理、医生管理、门诊管理、药店管理、药品管理、收费管理、医保管理、报表统计及病历电子化等功能模块。
|
5天前
|
架构师 Java 开发者
得物面试:Springboot自动装配机制是什么?如何控制一个bean 是否加载,使用什么注解?
在40岁老架构师尼恩的读者交流群中,近期多位读者成功获得了知名互联网企业的面试机会,如得物、阿里、滴滴等。然而,面对“Spring Boot自动装配机制”等核心面试题,部分读者因准备不足而未能顺利通过。为此,尼恩团队将系统化梳理和总结这一主题,帮助大家全面提升技术水平,让面试官“爱到不能自已”。
得物面试:Springboot自动装配机制是什么?如何控制一个bean 是否加载,使用什么注解?
|
1月前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
基于Java+Springboot+Vue开发的大学竞赛报名管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的大学竞赛报名管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
129 3
基于Java+Springboot+Vue开发的大学竞赛报名管理系统
|
1月前
|
前端开发 JavaScript Java
基于Java+Springboot+Vue开发的蛋糕商城管理系统
基于Java+Springboot+Vue开发的蛋糕商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的蛋糕商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
90 3
基于Java+Springboot+Vue开发的蛋糕商城管理系统
|
9天前
|
Java 测试技术 Spring
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
这篇文章介绍了Spring Boot中配置文件的语法、如何读取配置文件以及如何通过静态工具类读取配置文件。
16 0
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
|
24天前
|
Java 关系型数据库 数据库连接
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第3天】Spring Boot项目中数据库连接问题可能源于配置错误或依赖缺失。YAML配置文件的格式不正确,如缩进错误,会导致解析失败;而数据库驱动不匹配、连接字符串或认证信息错误同样引发连接异常。解决方法包括检查并修正YAML格式,确认配置属性无误,以及添加正确的数据库驱动依赖。利用日志记录和异常信息分析可辅助问题排查。
59 10
|
23天前
|
Java 关系型数据库 MySQL
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第4天】本文分析了Spring Boot应用在连接数据库时可能遇到的问题及其解决方案。主要从四个方面探讨:配置文件格式错误、依赖缺失或版本不兼容、数据库服务问题、配置属性未正确注入。针对这些问题,提供了详细的检查方法和调试技巧,如检查YAML格式、验证依赖版本、确认数据库服务状态及用户权限,并通过日志和断点调试定位问题。
|
29天前
|
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序列化)
|
12天前
|
Java Shell C++
Springboot加载注入bean的方式
本文详细介绍了Spring Boot中Bean的装配方法。首先讲解了使用@Component、@Service、@Controller、@Repository等注解声明Bean的方式,并解释了这些注解之间的关系及各自适用的层次。接着介绍了通过@Configuration和@Bean注解定义Bean的方法,展示了其灵活性和定制能力。最后讨论了@Component与@Bean的区别,并提供了在Spring Boot应用中装配依赖包中Bean的三种方法:使用@ComponentScan注解扫描指定包、使用@Import注解导入特定Bean以及在spring.factories文件中配置Bean。