草庐IT

springboot加载外部配置文件(properties、yml)

冯坤鹏11 2023-04-14 原文

1.前言

通过PropertySourceLoader接口的实现类配合监听器实现加载外部的配置文件,加载properties文件使用PropertiesPropertySourceLoader,加载yml文件使用YamlPropertySourceLoader。.通过监听器将配置文件加载到Spring环境配置中,且可以指定优先级。核心是将配置文件加载PropertySource中并将其添加到spring的MutablePropertySources中,使其可以通过@value等方式获取配置文件中的属性值。

2.加载properties文件

-----1.方法一:PropertiesPropertySourceLoader

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("publicConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

-----2.方法二:PropertiesFactoryBean

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        try {
            factoryBean.setLocation(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties"))));
            Properties object = factoryBean.getObject();
            if(object != null){
                PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
                configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

3.加载yml文件

-----1.方法一:YamlPropertySourceLoader

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {

        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

-----2.方法二:YamlPropertiesFactoryBean

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        try {
            factoryBean.setResources(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml"))));
            Properties object = factoryBean.getObject();
            if(object != null){
                PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
                configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.配置优先级

通过上述代码可以发现所有方法最后都是通过configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource)将封装好的PropertySource对象加入到Spring配置中的,而都是通过调用addFirst(PropertySource  propertySource),除了addFirst还有addLast,addBefore,addAfter,这就与优先级有关系了,先说一下addBefore和addAfter,这两个方法参数都是String relativePropertySourceName, PropertySource<?> propertySource,意思就是要将此propertySource添加在名为relativePropertySourceName的propertySource的前边还是后边,放在前边的在读取属性时会优先读取属性值,而addFirst和addLast则是将此propertySource放在整个列表的最前或最后。

对于优先读取该属性的值的解释:

例如项目中的配置文件application.yml中有属性name: zhangsan,外部配置文件externalApplication.yml中有属性name: lisi,通过上述任何方式将外部配置文件加载到Spring配置中后因为两个配置文件中都有name属性,但其值不相同,这个时候如果通过@Value("${name}")取值会取到zhangsan还是lisi呢,答案是在上述PropertySource列表中靠前的会优先生效。如果想让外部的配置文件优先则可以使用addFirst方法添加propertySource。

提到配置文件的优先级就想起了springboot默认读取配置文件的优先级,参考下方说明和链接:

优先级依次递减

1.在执行命令的目录下建config文件夹,然后把配置文件放到这个文件夹下。(在jar包的同一个目录下建config文件夹,执行命令需要在jar包所在目录下才行)
2.直接把配置文件放到jar包的同级目录
3.在classpath下建一个config文件夹,然后把配置文件放进去。
4.在classpath下直接放配置文件。

参考文章:http://t.csdn.cn/ufapd

5.使用的监听器以及加载的时机(监听的事件)

无论使用那种监听器的实现类型,都需要拿到ConfigurableEnvironment这个参数,可以在多个时机加载配置文件,例如environmentPrepared,contextPrepared,下面展示三种方式实现

方法一:

public class MyApplicationContextInitializer implements ApplicationContextInitializer {

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

需要将该类的全限定名配置到spring.factories中

org.springframework.context.ApplicationContextInitializer=com.fkp.springboot_listener.listener.MyApplicationContextInitializer

方法二:

public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    private final SpringApplication springApplication;

    private final String[] args;

    public MySpringApplicationRunListener(SpringApplication springApplication, String[] args) {
        this.springApplication = springApplication;
        this.args = args;
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("SpringApplicationRunListener....starting");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            environment.getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....started");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....running");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener....failed");
    }
}

需要将该类的全限定名配置到spring.factories中

org.springframework.boot.SpringApplicationRunListener=com.fkp.springboot_listener.listener.MySpringApplicationRunListener

方法三:

public class MyApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            applicationEnvironmentPreparedEvent.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

需要将该类的全限定名配置到spring.factories中

org.springframework.context.ApplicationListener=com.fkp.springboot_listener.listener.MyApplicationListener

备注:通过Environment取Spring配置中的值

Environment或实现该接口的类可以通过多种方式获取,例如上述ApplicationEnvironmentPreparedEvent#getEnvironment()获取ConfigurableEnvironment

通用的一种方法是通过ApplicationContext获取,ApplicationContext#getEnvironment(),ApplicationContext可以从Spring容器中取。

通过Environment的getProperty方法可以取Spring配置中属性的值。

有关springboot加载外部配置文件(properties、yml)的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  9. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐