如何实现动态@ConfigurationProperties前缀

Sau*_*abh 5 spring-boot

我要求将动态环境名称作为配置属性的前缀传递.我将从命令行传递环境作为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

environmentDetails.yml

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

environment:
  brokerUrl: http://ip:port
  queueName: testQueue
  receiverUserName: testuser
  receiverPassword: password
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 0

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

\n\n
\n

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

\n
\n\n

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

\n

  • 感谢布莱恩的帮助。我评论了@PropertySource(“environmentDetails.yml”),如果我使用前缀的硬编码值,例如@ConfigurationProperties(prefix =“envName”),它工作正常。但是当我使用前缀的占位符值时,例如 @ConfigurationProperties(prefix="${envName}")。它给了我一个错误。有什么方法可以将前缀与动态值一起使用。根据要求,我将有许多来自其中包含环境名称的源的文件,并且我需要根据来自文件名的环境选择属性。所以环境名称将是动态的。 (2认同)