Skip to content
Advertisement

Inject system environment variable into Spring Annotation with placeholder

I know you can inject environment variables with the @Value annotation like this

    @Value("#{systemEnvironment['AWS_ENV']}")
    private String envTarget;

If I am using a Spring annotation however can I inject the environment variable in-line into the String value? For example something like this:

@PropertySource("classpath:secrets-${#{systemEnvironment['AWS_ENV']}.properties")

Obviously the above doesn’t work as it tries to resolve systemEnvironment['AWS_ENV'] as a jvm property. Anyone have any ideas?

Advertisement

Answer

The placeholder could be moved to a single aws.properties file:

aws.properties 
envTarget = ${AWS_ENV}

then:

@PropertySource("classpath:aws.properties")

For local development, the placeholder can be added as JVM parameters in the run configuration, but that can become a pain to manage. An alternative would be to have a aws-local.properties (located in same resources folder), but this file is in .gitignore so secrets are never committed. Then there is a single JVM parameter to use the local profile.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement