玩转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 分钟前
Java扩展——OkHttp
java·开发语言·okhttp
卓怡学长7 分钟前
w210基于springboot反诈平台设计与实现
java·spring boot·spring·intellij-idea
萧瑟余晖17 分钟前
Java深入解析篇六十一之编译器API(javax.tools)详解
java·开发语言
码云数智-园园42 分钟前
C++ STL 容器怎么选?vector、list、map、unordered_map 优缺点对比
java·开发语言
en.en..1 小时前
竖线 |:管道、按位或、掩码组合
java·开发语言
程序猿乐锅1 小时前
【计算机组成原理 | 第六章】中央处理器 CPU
java·开发语言
大模型丫丫1 小时前
如何提升单体 Spring Boot 应用的并发数?
java·spring boot·后端
Terra.K2 小时前
ThreadLocal解决一个线程里面跨层传递问题
java·开发语言·后端
泡海椒2 小时前
低代码规则开发:JQuick-Java声明式配置驱动开发落地教程
java·低代码·rxjava
weixin_440730502 小时前
socket解决多次输入问题-大数据接收问题-模块动态导入
java·开发语言·servlet