Spring应用程序中的可选环境变量 [英] Optional environment variables in Spring app

查看:124
本文介绍了Spring应用程序中的可选环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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}".然后,@ValuesomeProp评估为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).

Spring SpEL表达式模板.

来自外部化配置

最后,虽然您可以在@Value中编写SpEL表达式,例如 表达式不是从应用程序属性文件处理的.

Finally, while you can write a SpEL expression in @Value, such expressions are not processed from Application property files.

这篇关于Spring应用程序中的可选环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆