简体   繁体   English

使用占位符将系统环境变量注入 Spring Annotation

[英]Inject system environment variable into Spring Annotation with placeholder

I know you can inject environment variables with the @Value annotation like this我知道您可以像这样使用@Value注释注入环境变量

    @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?但是,如果我使用的是 Spring 注释,我可以将环境变量内嵌到 String 值中吗? 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.显然,上面的方法不起作用,因为它试图将systemEnvironment['AWS_ENV']解析为 jvm 属性。 Anyone have any ideas?谁有想法?

The placeholder could be moved to a single aws.properties file:占位符可以移动到单个 aws.properties 文件中:

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.对于本地开发,可以在运行配置中添加占位符作为 JVM 参数,但这可能会变得难以管理。 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.另一种方法是使用 aws-local.properties(位于同一资源文件夹中),但此文件位于 .gitignore 中,因此永远不会提交机密。 Then there is a single JVM parameter to use the local profile .然后有一个 JVM 参数来使用本地配置文件

While the accepted answer did partially solve my problem I ended up just manually configuring the Properties without using the PropertySource annotation.虽然接受的答案确实部分解决了我的问题,但我最终只是在不使用 PropertySource 注释的情况下手动配置了属性。 This allowed me to have better control over the bean lifecycles and the property file to load.这让我可以更好地控制 bean 生命周期和要加载的属性文件。

Spring Environment Property Source Configuration Spring 环境属性源配置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM