玩转springboot之springboot加载自定义yml配置文件

加载自定义yml配置文件

springboot默认加载的是application.yml/properties配置文件,对于自定义的properties配置文件使用@PropertySource和@ConfigurationProperties注解搭配使用也可以进行加载注入,但是properties配置文件没有yml配置文件有层次感,如果使用自定义的yml配置文件却发现springboot并没有将yml中的配置属性注入进去

这里可以自定义PropertySourceFactory来加载yml(本质就是自己解析yml配置文件,转换成Properties)

复制代码
public class YmlPropertyFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, @NotNull EncodedResource resource) throws IOException {
      // 将yml配置转换为Properties
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        // 文件未找到使用默认的配置读取
        if (propertiesFromYaml == null) {
            return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
        }
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if(sourceName == null){
            log.error("获取资源失败");
            throw new RuntimeException("加载资源失败"+resource);
        }
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            log.error("加载{}文件失败,请检查是否有该文件", resource.getResource().getFilename());
            return null;
        }
    }
}

在使用的时候,就像使用自定义的properties配置文件类似

复制代码
@PropertySource("classpath:custom.yml")
// factory指定自定义解析yml的PropertySourceFactory实现类
@ConfigurationProperties(factory=YmlPropertyFactory.class,prefix = "custom")
@Data
public class CustomProperties {
    private Map<String,String> typeFileds;
    private String name;

}

https://zhhll.icu/2021/框架/springboot/基础/14.加载自定义yml配置文件/

本文由mdnice多平台发布

相关推荐
豆沙沙包?1 小时前
C++-程序的内存模型(P84-P88)
java·jvm·c++
吴声子夜歌1 小时前
正则指引——匹配原理
java·正则表达式
未秃头的程序猿2 小时前
凌晨3点被叫醒:线上OOM,我用这套流程40分钟定位根因
java·jvm·后端
letisgo52 小时前
JDK21 + Spring AI 2.0 入场指南:2026 年 Java 开发者 AI 架构全景图
java·ai·idea·jdk21
白仑色2 小时前
Spring Boot 从切面统一控制事务
java·spring boot·aop·spring事务
Flynt3 小时前
Java并行流,让我debug了一整天
java
DFT计算杂谈3 小时前
FeSe超薄膜在CaF2衬底上的电子结构DFT研究
java·服务器·前端
circuitsosk3 小时前
长文本与高并发下的Token“瘦身”策略:Prompt压缩与上下文窗口优化
java·前端·python·prompt·上下文窗口·token优化
岁岁养乐多3 小时前
LangChain4j 工厂模式
java·开发语言
小小小米粒3 小时前
idea常用搭配
java