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

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

问题描述

我有从外部配置 web-service 获取的 jdbc 属性文件在 spring boot 中,为了设置 mysql props,将它们添加到 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?

同样适用于 Spring-batch 道具:

same goes for Spring-batch props:

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天全站免登陆