玩转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多平台发布

相关推荐
亦暖筑序19 分钟前
AgentScope-Java 入门:用 SSE 展示评审任务进度
java·agent·ai编程
卓怡学长33 分钟前
w261springboot基于web学校课程管理系统
java·数据库·spring boot·spring·intellij-idea
shuoshuohaohao34 分钟前
《JavaWeb --2》
java
浩瀚地学34 分钟前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
AI人工智能+电脑小能手41 分钟前
【大白话说Java面试题 第169题】【07_Redis篇】第5题:如何保证缓存一致性?
java·redis·延迟双删·缓存一致性·双写一致性
SimonKing1 小时前
Spring I18N 底层源码大揭秘:你的 MessageSource 到底是怎么找到配置的?
java·后端·程序员
极客先躯1 小时前
高级java每日一道面试题-2026年04月04日-实战篇[Docker]-如何排查容器存储挂载失败的问题?
java·运维·docker·容器·高级面试
Hesionberger1 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
CodeStats1 小时前
【Linux IO】从文件描述符到硬件中断:Linux IO 系统底层完全拆解
java·linux·开发语言·io·socket
大阿明1 小时前
C++智能指针与RAII机制精讲:彻底根治内存泄漏与野指针
java·jvm·c++