springboot如何通过@PropertySource加载自定义yml文件

目录
  • @PropertySource加载自定义yml文件
  • @PropertySource注解对于yml的支持

@PropertySource加载自定义yml文件

使用@PropertySource默认加载的是.xml或者 .properties文件,因为在注解源码默认使用的是DefaultPropertySourceFactory实现处理文件内容,spring使用ResourcePropertySource从Resource构建Properties传给Spring。

系统的应用,比如加载自定义的文件,将配置文件内容存储在内存,如下:

那么加载一个自定义的.yml文件,就需要自定义实现ResourcePropertySource来处理yml文件的类

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }
    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

@PropertySource注解对于yml的支持

@PropertySource只对properties文件可以进行加载,但对于yml或者yaml不能支持。

追寻源码。

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

我们只需要继承DefaultPropertySourceFactory类并修改就可以了。

public class YamlConfigFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }
    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}
@PropertySource(value = {"classpath:dog.yml"},factory = YamlConfigFactory.class)
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
    private String name ;
    private String age ;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • 详解Spring Boot 自定义PropertySourceLoader

    SpringBoot 的配置文件内置支持 properties.xml.yml.yaml 几种格式,其中 properties和xml 对应的Loader类为 PropertiesPropertySourceLoader ,yml和yaml 对应的Loader类为 YamlPropertySourceLoader. 观察这2个类可以发现,都实现自接口 PropertySourceLoader .所以我们要新增支持别的格式的配置文件,就可以通过实现接口 PropertySourceLoader 来

  • SpringBoot四种读取properties文件的方式(小结)

    前言 在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作.今天就分享四种在Springboot中获取配置文件的方式. 注:前三种测试配置文件为springboot默认的application.properties文件 #######################方式一######################### com.zyd.type3=Springboot - @ConfigurationProperties com.zyd.title3=使用@Configura

  • 在SpringBoot下读取自定义properties配置文件的方法

    SpringBoot工程默认读取application.properties配置文件.如果需要自定义properties文件,如何读取呢? 一.在resource中新建.properties文件 在resource目录下新建一个config文件夹,然后新建一个.properties文件放在该文件夹下.如图remote.properties所示 二.编写配置文件 remote.uploadFilesUrl=/resource/files/ remote.uploadPicUrl=/resource

  • springboot如何通过@PropertySource加载自定义yml文件

    目录 @PropertySource加载自定义yml文件 @PropertySource注解对于yml的支持 @PropertySource加载自定义yml文件 使用@PropertySource默认加载的是.xml或者 .properties文件,因为在注解源码默认使用的是DefaultPropertySourceFactory实现处理文件内容,spring使用ResourcePropertySource从Resource构建Properties传给Spring. 系统的应用,比如加载自定义的

  • mybatis 运行时加载自定义mapper文件方式

    mybatis 运行时加载自定义mapper文件 用mybatis一定要写mapper文件,这是使用mybatis的常识,但有时候应用需求,mapper文件中的节点需要动态生成,或者根据业务场景进行组装,那这个时候的SQL语句直接写在mapper文件显然不可取,又或者采用动态SQL完成,今天介绍一种方式,支行时加载自定义mapper配置文件. 我首先介绍一种mapper文件存在的写法,也是大家常用的,至于spring-mybatis配置方法,我这里就不列了: dao接口: package com

  • 解决SpringBoot webSocket 资源无法加载、tomcat启动报错的问题

    问题描述: 1. 项目集成WebSocket,且打包发布tomcat时出现websocket is already in CLOSING or CLOSE state这样的问题,建议参考"解决方法二",但是"解决方法一"请要了解查看 ,因为解决方法二是在一的基础上进行更正 2. 如果出现javax.websocket.server.ServerContainer not available这样的错误,请参考"解决方法一"中步骤3 解决方法一:(常

  • springboot启动不加载bootstrap.yml文件的问题

    目录 springboot启动不加载bootstrap.yml文件 无法识别 bootstrap.yml 小绿叶问题 错误信息 问题定位 解决 springboot启动不加载bootstrap.yml文件 使用nacos做配置中心,但是程序启动失败,没有拉取配置中心的配置信息. 检查之后发现是bootstrap.yml文件没有被加载,在项目的pom.xml文件中添加如下依赖,可能需要添加版本号,具体版本号可以去maven仓库查询,我使用的是 3.0.1版本. <dependency> <

  • springboot加载一个properties文件转换为map方式

    目录 加载一个properties文件转换为map 1.创建一个properties文件 2.在java中将该properties文件转换为map properties配置文件出现乱码 加载一个properties文件转换为map springboot中比较常见的获取properties中的值,就是直接在字段上面添加@Value的属性. 但有时候我们不确定key有多少,但是会有一定的规律(这个规律是根据业务来定的,如下),这时候我们就可以考虑将properties中的信息转换为一个map,然后根

  • vue加载自定义的js文件方法

    在做项目中需要自定义弹出框.就自己写了一个. 效果图 遇见的问题 怎么加载自定义的js文件 vue-插件这必须要看.然后就是自己写了. export default{ install(Vue){ var tpl; // 弹出框 Vue.prototype.showAlter = (title,msg) =>{ var alterTpl = Vue.extend({ // 1.创建构造器,定义好提示信息的模板 template: '<div id="bg">' + '&

  • python加载自定义词典实例

    如下所示: #加载词典 def load_dict_from_file(filepath): _dict = {} try: with io.open(filepath, 'r',encoding='utf-8') as dict_file: for line in dict_file: (key, value) = line.strip().split(' ') #将原本用空格分开的键和值用冒号分开来,存放在字典中 _dict[key] = value except IOError as io

  • pytorch加载自定义网络权重的实现

    在将自定义的网络权重加载到网络中时,报错: AttributeError: 'dict' object has no attribute 'seek'. You can only torch.load from a file that is seekable. Please pre-load the data into a buffer like io.BytesIO and try to load from it instead. 我们一步一步分析. 模型网络权重保存额代码是:torch.sa

  • 如何正确控制springboot中bean的加载顺序小结篇

    1.为什么需要控制加载顺序 springboot遵从约定大于配置的原则,极大程度的解决了配置繁琐的问题.在此基础上,又提供了spi机制,用spring.factories可以完成一个小组件的自动装配功能. 在一般业务场景,可能你不大关心一个bean是如何被注册进spring容器的.只需要把需要注册进容器的bean声明为@Component即可,spring会自动扫描到这个Bean完成初始化并加载到spring上下文容器. 而当你在项目启动时需要提前做一个业务的初始化工作时,或者你正在开发某个中间

  • SpringBoot项目实战之加载和读取资源文件

    目录 通过Resource接口 手动加载 通过@Value自动转换 通过ResourceLoader加载 使用ResourceUtils加载资源 读取资源中的内容 通过File对象读取 通过InputStream对象读取 文末总结 本文聊一聊在 SpringBoot 应用中,访问加载类路径(classpath)中的文件内容的多种方法. 通过Resource接口 Resource接口抽象出一种更底层的方式管理资源,可以实现通过统一的方式处理各类文件资源.下面是几种获取资源实例的方法. 手动加载 访

随机推荐