【问题标题】:How to implement dynamic @ConfigurationProperties Prefix如何实现动态@ConfigurationProperties Prefix
【发布时间】:2018-01-15 08:43:32
【问题描述】:

我需要将动态环境名称作为配置属性的前缀传递。我将从命令行将环境作为 VM 参数传递,并且应该为该环境加载所有属性。

我的配置

@Configuration
@EnableConfigurationProperties
@PropertySource("environmentDetails.yml")
@ConfigurationProperties(prefix="${environment}")
public class ConfigurationBean {

    private String brokerUrl;
    private String queueName;
    private String receiverUserName;
    private String receiverPassword;

    public String getBrokerUrl() {
        return brokerUrl;
    }
    public void setBrokerUrl(String brokerUrl) {
        this.brokerUrl = brokerUrl;
    }
    public String getQueueName() {
        return queueName;
    }
    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }
    public String getReceiverUserName() {
        return receiverUserName;
    }
    public void setReceiverUserName(String receiverUserName) {
        this.receiverUserName = receiverUserName;
    }
    public String getReceiverPassword() {
        return receiverPassword;
    }
    public void setReceiverPassword(String receiverPassword) {
        this.receiverPassword = receiverPassword;
    }
}

environmentDetails.yml

spring:
  profiles.active: default
---
spring:
  profiles: default

environment:
  brokerUrl: http://ip:port
  queueName: testQueue
  receiverUserName: testuser
  receiverPassword: password

【问题讨论】:

  • 谢谢布赖恩。当我使用 ${environment} 作为@ConfigurationProperties 的参数时,它不起作用。有什么技巧可以使用我可以通过程序中的程序/VM参数传递的动态参数?我在 Spring 应用程序中做了同样的事情,它工作正常,但在 Spring 启动的情况下,它不起作用。
  • @Saurabh,您找到解决方案了吗,如何使用 VMArg 设置“ConfigurationProperties 前缀”?
  • 我认为你应该使用一些Map<String, BrokerProperties>,其中 key 是你的动态环境变量。该地图可以收集带有broker.*前缀的属性(如broker.a.broker-urlbroker.b.broker-url

标签: spring-boot


【解决方案1】:

问题是:您不能将 .yml 与 @PropertySource 一起使用:boot-features-external-config-yaml-shortcomings

YAML 文件无法通过 @PropertySource 注解加载。因此,如果您需要以这种方式加载值,则需要使用属性文件。

您必须转换为 .properties 才能执行此操作。

【讨论】:

  • 感谢布赖恩的帮助。我评论了 @PropertySource("environmentDetails.yml") 如果我使用硬编码值作为前缀,它工作正常,例如@ConfigurationProperties(prefix="envName")。但是当我使用占位符值作为前缀时,例如@ConfigurationProperties(prefix="${envName}")。它给了我一个错误。有什么办法可以将前缀与动态值一起使用。根据要求,我将有许多来自具有环境名称的源的文件,并且我需要根据来自文件名的环境选择属性。所以环境名称将是动态的。
  • 今天仍然如此吗?
猜你喜欢
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2020-08-09
相关资源
最近更新 更多