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

相关推荐
sheji341611 分钟前
【开题答辩全过程】以 婚纱影楼管理系统为例,包含答辩的问题和答案
java·eclipse
LuDvei13 分钟前
LINUX文件操作函数
java·linux·算法
葵续浅笑1 小时前
从Spring拦截器到Filter过滤器:一次报文修改加解密的填坑经验
java·后端·spring
J2虾虾1 小时前
Spring Boot中使用@Scheduled做定时任务
java·前端·spring boot
肉肉不想干后端1 小时前
联合订单并发退款:一次分布式锁冲突的排查与思考
java
用户4745189475102 小时前
全链路日志追踪利器:trace-spring-boot-starter 实战指南
java
acx匿2 小时前
【Windows10 下 JDK17 环境变量配置超详细教程(ZIP 版)】
java·jdk
Renhao-Wan2 小时前
Java 算法实践(七):动态规划
java·算法·动态规划
新缸中之脑2 小时前
Sonnet 4.6 vs Opus 4.6
java·开发语言
曹牧2 小时前
Java:@RequestBody 和 @RequestParam混合使用
java·开发语言