玩转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 分钟前
114. 二叉树展开为链表
java·数据结构·算法·链表·职场和发展·深度优先
csdn2015_23 分钟前
mybatisplus自动生成id
java·mybatis
时艰.25 分钟前
电商订单系统设计与实现
java
sheji341625 分钟前
【开题答辩全过程】以 基于Java的网上书店销售系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
石去皿36 分钟前
数据结构与算法面试核心考点精要
java·算法·面试
学Linux的语莫1 小时前
skills的使用
java·数据库·python
大模型玩家七七1 小时前
关系记忆不是越完整越好:chunk size 的隐性代价
java·前端·数据库·人工智能·深度学习·算法·oracle
一 乐1 小时前
林业资源管理|基于java + vue林业资源管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·林业资源管理系统
lipiaoshuigood1 小时前
微服务生态组件之Spring Cloud LoadBalancer详解和源码分析
java·spring cloud·微服务
Geoking.1 小时前
什么是乐观锁?原理、实现方式与实战详解
java·开发语言