如何以编程方式覆盖Spring Boot application.properties? [英] How can I override Spring Boot application.properties programmatically?

查看:56
本文介绍了如何以编程方式覆盖Spring Boot application.properties?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从外部配置Web服务获取的jdbc属性文件 在春季启动中,为了设置mysql属性,可以很容易地将它们添加到application.properties:

I have jdbc property files which I take from external configuration web-service In spring boot in order to set mysql props it's easy as adding those to application.properties:

spring.datasource.url=jdbc:mysql://localhost/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

如何在我的应用中以编程方式覆盖这些内容?

How could I override those programticlly in my app?

春季批道具也一样:

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost/mydv
database.username=root
database.password=root

推荐答案

您可以在对ApplicationEnvironmentPrepared事件做出反应的生命周期侦听器中添加其他属性源.

You can add additional property sources in a lifecycle listener reacting to ApplicationEnvironmentPrepared event.

类似的东西:

public class DatabasePropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
  public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    ConfigurableEnvironment environment = event.getEnvironment();
    Properties props = new Properties();
    props.put("spring.datasource.url", "<my value>");
    environment.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
  }
}

然后在src/main/resources/META-INF/spring.factories中注册该类:

Then register the class in src/main/resources/META-INF/spring.factories:

org.springframework.context.ApplicationListener=my.package.DatabasePropertiesListener

这对我有用,但是,由于在应用程序启动阶段还处于初期,您在此时只能做些限制,因此您必须找到一种无需依赖即可获取所需值的方法.在其他四季豆等上.

This worked for me, however, you are sort of limited as to what you can do at this point as it's fairly early in the application startup phase, you'd have to find a way to get the values you need without relying on other spring beans etc.

这篇关于如何以编程方式覆盖Spring Boot application.properties?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆