【问题标题】:Can I specify default values for a config.yml on my java application?我可以在我的 java 应用程序上为 config.yml 指定默认值吗?
【发布时间】:2018-12-18 19:47:36
【问题描述】:

我目前正在使用 dropwizard 处理我的 java 应用程序。

它工作正常,我运行它发送一个完整的 yml 文件或参数。

因此,例如,其中之一就是这个:

reporting:
  enabled: false

所以,我想做的是将此 yml 文件设为我的默认值,并在需要时(用于将来的功能)发送此 var 的值

所以我想做这样的事情

reporting:
  enabled: ${REPORTING_FLAG:false}

然后我可以发送 REPORTING_FLAG 作为环境参数(docker)并且应该可以正常工作....

问题是我的应用无法识别此模型。

有什么办法可以做到这一点吗?是否需要考虑额外的配置?我以前用 spring 应用程序做过,但这似乎有所不同。

现在我收到一个错误,即预期的布尔值无效(将整行作为字符串)

想法?

【问题讨论】:

  • 你是显式查询getParameter("reporting.enabled"),还是有像Spring的@ConfigurationProperties这样的绑定机制?
  • 不是春天,但我确实有类似@Value的东西

标签: java yaml dropwizard


【解决方案1】:

所以,在阅读了更多 dropwizard 文档后,我发现:https://www.dropwizard.io/0.8.2/docs/manual/core.html

环境变量

dropwizard-configuration 模块还提供了使用 SubstitutingSourceProvider 和 EnvironmentVariableSubstitutor 将配置设置替换为环境变量值的功能。

public class MyApplication extends Application<MyConfiguration> {
    // [...]
    @Override
    public void initialize(Bootstrap<MyConfiguration> bootstrap) {
        // Enable variable substitution with environment variables
        bootstrap.setConfigurationSourceProvider(
                new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
                                                   new EnvironmentVariableSubstitutor()
                )
        );

    }

    // [...]
}

需要替换的配置设置需要在配置文件中明确写入,并遵循 Apache Commons Lang 库中 StrSubstitutor 的替换规则。

mySetting: ${DW_MY_SETTING}
defaultSetting: ${DW_DEFAULT_SETTING:-default value}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 2017-03-09
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2012-06-24
    相关资源
    最近更新 更多