Spring应用程序中的可选环境变量 [英] Optional environment variables in Spring app
问题描述
在我的Spring Boot应用程序的application.properties
中,我具有以下定义:
In my Spring Boot app's application.properties
I have this definition:
someProp=${SOME_ENV_VARIABLE}
但这是一个可选值,仅在某些环境中设置,我像这样使用它
But this is an optional value only set in certain environments, I use it like this
@Value("${someProp:#{null}}")
private String someProp;
令人惊讶的是,当我看到env时,出现了这个错误. var不存在
Could not resolve placeholder 'SOME_ENV_VARIABLE' in string value "${SOME_ENV_VARIABLE}"
如果没有在任何PropertySource
中找到,我期望Spring只是设置一个空白值.
Surprisingly I get this error when the env. var doesn't exist
Could not resolve placeholder 'SOME_ENV_VARIABLE' in string value "${SOME_ENV_VARIABLE}"
I was expecting Spring to just set a blank value if not found in any PropertySource
.
如何使其可选?
推荐答案
在application.properties
someProp=${SOME_ENV_VARIABLE:#{null}}
像@Value("${someProp})
一样使用时,它将正确评估为null
.首先,如果在处理application.properties
时未找到SOME_ENV_VARIABLE
,则其值将成为字符串文字#{null}".然后,@Value
将someProp
评估为SpEL表达式,结果为null
.可以通过查看Environment
bean中的属性来验证实际值.
When used like @Value("${someProp})
, this will correctly evaluate to null
. First, if SOME_ENV_VARIABLE
is not found when application.properties
is being processed, its value becomes the string literal "#{null}". Then, @Value
evaluates someProp
as a SpEL expression, which results in null
. The actual value can be verified by looking at the property in the Environment
bean.
This solution utilizes the default value syntax specified by the PlaceholderConfigurerSupport
class
可以为每个配置程序全局定义默认属性值 通过properties属性或按属性分配实例 使用默认值分隔符(默认情况下为:") 可通过setValueSeparator(String)进行自定义.
Default property values can be defined globally for each configurer instance via the properties property, or on a property-by-property basis using the default value separator which is ":" by default and customizable via setValueSeparator(String).
来自外部化配置
最后,虽然您可以在@Value中编写SpEL表达式,例如 表达式不是从应用程序属性文件处理的.
Finally, while you can write a SpEL expression in @Value, such expressions are not processed from Application property files.
这篇关于Spring应用程序中的可选环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!