本文介绍了如何实现动态@ConfigurationProperties 前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a requirement to pass dynamic environment name as a prefix of configuration property. I will pass environment as VM argument from command line and all properties should be loaded for that environment.

我的配置:

@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

推荐答案

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

Here is the issue: You can't use .yml with @PropertySource: boot-features-external-config-yaml-shortcomings

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

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

You'll have to convert to .properties to do this.

这篇关于如何实现动态@ConfigurationProperties 前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 20:39