javadropwizard

In dropwizard configuration am I allowed to use environment variable as default?


I couldn't find any documentation for this. For example, I know this is possible:

defaultSetting: ${DW_DEFAULT_SETTING:-default value}

But what if I want logic to say if DW_DEFAULT_SETTING is not defined, then use another env variable

defaultSetting: ${DW_DEFAULT_SETTING:-${ANOTHER_SETTING}}

Is this possible? The only other alternative I can think of is defining a custom getter for defaultSetting in my Configuration class which would read system env variables.


Solution

  • Technically, it should be possible.

    How to enable it

    You could use the constructor EnvironmentVariableSubstitutor​(boolean strict, boolean substitutionInVariables) with the second argument as true to enable substitution inside variables.

    For bootsrapping your app with this special EnvironmentVariableSubstitutor​ instance, see WarFox's answer in related question Overriding server connector config with env variables with dropwizard.

    The SubstitutingSourceProvider to use environment variables inside YAML files is explained here: Can I specify default values for a config.yml on my java application?.

    How it works

    Dropwizard Configuration uses Apache Commons Text

    Responsible for environment variable substitution is the class EnvironmentVariableSubstitutor.

    It is implemented by inheritance and uses Apache Commons Text: extends StringSubstitutor.

    StringSubstitutor allows recursive resolution

    From StringSubstitutor 's JavaDoc:

    Using Recursive Variable Replacement

    Variable replacement can work recursively by calling setEnableSubstitutionInVariables(boolean) with true. If a variable value contains a variable then that variable will also be replaced. Cyclic replacements are detected and will throw an exception.

    You can get the replace result to contain a variable prefix. For example:

    "The variable ${${name}} must be used."

    If the value of the "name" variable is "x", then only the variable "name" is replaced resulting in:

    "The variable ${x} must be used."