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

相关推荐
吴声子夜歌3 分钟前
Java——类、对象及方法(一)
java·开发语言
程序员夏洛11 分钟前
Redis 的持久化机制有哪些?
java·数据库·redis
凯尔萨厮18 分钟前
Java学习笔记十(注解)
java·笔记·学习
钱栈up33 分钟前
VSCode 调试多模块 Maven + Spring Boot 后端:从启动失败到一次跑通
java·spring boot·maven
uoKent34 分钟前
c++中new和malloc的区别
java·jvm·c++
十五喵源码网44 分钟前
基于springboot2+vue2的疾病防控综合系统
java·毕业设计·springboot·论文笔记
砚底藏山河1 小时前
【量化纯GET实战 #11】移动均线 MA:5 日 20 日 60 日怎么算怎么用
java·python·金融·maven
一只小闪闪1 小时前
easy-trans java数据通用翻译框架v2.3.0
java·后端·架构
2601_962055811 小时前
Spring全部注解
java·后端·spring
chjif1 小时前
一张照片和一段声音如何生成口播视频:MiniMax H3 音画同步实测
java·前端·javascript