将系统环境变量用占位符注入到Spring注解中

huangapple go评论81阅读模式
英文:

Inject system environment variable into Spring Annotation with placeholder

问题

我知道您可以使用 @Value 注解来注入环境变量,就像这样:

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

但是,如果我正在使用 Spring 注解,是否可以将环境变量内联注入到字符串值中呢?例如像这样:

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

显然,上面的方法不起作用,因为它尝试将 systemEnvironment['AWS_ENV'] 解析为 JVM 属性。有没有人有任何想法呢?

英文:

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?

答案1

得分: 0

以下是翻译好的内容:

占位符可以移动到单独的 aws.properties 文件中:

aws.properties 
envTarget = ${AWS_ENV}

然后:

@PropertySource("classpath:aws.properties")

对于本地开发,可以将占位符作为 JVM 参数添加到运行配置中,但这可能会变得很麻烦。另一种选择是拥有一个 aws-local.properties 文件(位于相同的资源文件夹中),但是该文件在 .gitignore 中,因此不会提交秘密信息。然后只需使用单个 JVM 参数来使用本地配置文件。

英文:

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.

答案2

得分: 0

虽然被接受的回答在一定程度上解决了我的问题,但我最终还是选择手动配置属性,而不使用PropertySource注解。这使我能够更好地控制bean的生命周期和要加载的属性文件。

链接:https://stackoverflow.com/questions/14416005/spring-environment-property-source-configuration

英文:

While the accepted answer did partially solve my problem I ended up just manually configuring the Properties without using the PropertySource annotation. This allowed me to have better control over the bean lifecycles and the property file to load.

https://stackoverflow.com/questions/14416005/spring-environment-property-source-configuration

huangapple
  • 本文由 发表于 2020年8月25日 19:56:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63578349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定