使用dropwizard中的env变量覆盖配置中的问题

时间:2016-10-05 11:53:37

标签: java environment-variables dropwizard

MyWebConfiguration.java将以下代码描述为drop wizard

public void initialize(Bootstrap<MyWebConfiguration> bootstrap) {
    LOG.info("Initializing configuration");
    // Enable variable substitution with environment variables
    bootstrap.setConfigurationSourceProvider(
       new SubstitutingSourceProvider(
           bootstrap.getConfigurationSourceProvider(),
             new EnvironmentVariableSubstitutor(false)
       )
   );
}

dev-services.yaml文件有

tokenSecret: ${TOKEN_SECRET}

但是当我运行应用程序并调试以检查我为tokenSecret获取的值时,它显示了tokenSecret =&#34; $ {TOKEN_SECRET}&#34;在调试控制台中。

我尝试更改MyWebConfiguration.java如下: -

bootstrap.setConfigurationSourceProvider(
       new SubstitutingSourceProvider(
           bootstrap.getConfigurationSourceProvider(),
             new EnvironmentVariableSubstitutor(true)// changed false to true
       )
   );

但是现在当我尝试运行程序时,它会显示以下错误

Exception in thread "main" io.dropwizard.configuration.UndefinedEnvironmentVariableException: The environment variable 'TOKEN_SECRET' is not defined; could not substitute the expression '${TOKEN_SECRET}'.
    at io.dropwizard.configuration.EnvironmentVariableLookup.lookup(EnvironmentVariableLookup.java:41)
    at org.apache.commons.lang3.text.StrSubstitutor.resolveVariable(StrSubstitutor.java:726)
    at org.apache.commons.lang3.text.StrSubstitutor.substitute(StrSubstitutor.java:649)
    at org.apache.commons.lang3.text.StrSubstitutor.substitute(StrSubstitutor.java:563)
    at org.apache.commons.lang3.text.StrSubstitutor.replace(StrSubstitutor.java:305)
    at io.dropwizard.configuration.SubstitutingSourceProvider.open(SubstitutingSourceProvider.java:39)
    at io.dropwizard.configuration.YamlConfigurationFactory.build(YamlConfigurationFactory.java:80)
    at io.dropwizard.cli.ConfiguredCommand.parseConfiguration(ConfiguredCommand.java:124)
    at io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:72)
    at io.dropwizard.cli.Cli.run(Cli.java:75)
    at io.dropwizard.Application.run(Application.java:79)

谁能告诉我哪里可能出错?

1 个答案:

答案 0 :(得分:1)

您的环境变量不会传播。从您的系统到您从中启动DropWizard的IDE没有自动传播。

其次,使用new EnvironmentVariableSubstitutor(false)(非严格)时,您需要提供默认值,即使它们应为空:

tokenSecret: ${TOKEN_SECRET:-}

缺少时,strict将抛出UndefinedEnvironmentVariableException,非严格将使用空字符串。