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

相关推荐
尽兴-9 分钟前
JVM垃圾收集器与三色标记算法详解
java·jvm·算法·cms·gc·g1·三色标记算法
Anastasiozzzz14 分钟前
Redis脑裂问题--面试坑点【Redis的大脑裂开?】
java·数据库·redis·缓存·面试·职场和发展
tkevinjd17 分钟前
4-初识Maven
java·maven
ckhcxy18 分钟前
抽象类和接口(二)
java
短剑重铸之日20 分钟前
《SpringCloud实用版》 Gateway 4.3.x 保姆级实战:路由 + 限流 + 鉴权 + 日志全覆盖
java·后端·spring cloud·架构·gateway
高山上有一只小老虎22 分钟前
mybatisplus实现简单的增删改查方法
java·spring boot·后端
ZealSinger23 分钟前
Nacos2.x 内存注册表:从服务调用链路深入理解
java·spring boot·spring·spring cloud·nacos
编程彩机30 分钟前
互联网大厂Java面试:从微服务到分布式事务的技术深度解析
java·spring cloud·微服务·分布式事务·saga·电商平台
阿蒙Amon33 分钟前
C#每日面试题-break、continue和goto的区别
java·面试·c#
葡萄成熟时 !37 分钟前
JDK时间类
java·开发语言