如何在Spring Boot中在application.yml中定义默认的空值 [英] How to define default null value in application.yml in Spring Boot
问题描述
我正在尝试使用SpringBoot版本1.3.0.RELEASE在application.yml中将默认值定义为空值。该目标可以使用带有 ConfigurationProperties
批注的类
I'm trying to define the default value as null value in application.yml with SpringBoot version 1.3.0.RELEASE. The goal is be able to refer it with a class with ConfigurationProperties
annotation
-- application.yml --
test.foo: ${test.bar:#{null}}
但它不起作用。
如果 test.bar
的值不正确定义后,将 test.foo
设置为null(默认值)
If the value of test.bar
is not defined, set test.foo
to null (default value)
我的依赖项中已经有spring-el了。我不想使用 PropertyPlaceholderConfigurer.setNullValue
I already have spring-el in my dependencies. I don't want to use PropertyPlaceholderConfigurer.setNullValue
在中似乎可以使用值
,但不在 application.yml
中(请参见 http://farenda.com/spring/spring-inject-null-value/ )
It's seem to work in @Value
but not in application.yml
(see http://farenda.com/spring/spring-inject-null-value/)
这是一个错误,还是yaml不是为此设计的?
我尝试了 http://yaml.org/type/null.html,但它也不起作用
It's a bug, or yaml is not designed for that? I tried all values in http://yaml.org/type/null.html but it doesn't worked either
谢谢
推荐答案
@值
从文档中,我们可以看到:
@Value
From the document, we can see:
一个常见用例是使用#{systemProperties.myProp}样式表达式分配默认字段值。
A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.
此处实际上分为三个阶段:
It is actually three phases here:
- Spring获得注释字符串-
AutowiredAnnotationBeanPostProcessor
- Spring通过注释元数据获取属性值-
环境
- Spring解释属性值-
ExpressionParser
- Spring get the annotation string --
AutowiredAnnotationBeanPostProcessor
- Spring get property value by the annotation meta data --
Environmen
- Spring interpret the property value --
ExpressionParser
如果我们在 application.yml
中定义了 test.foo
,就像您描述的那样:
If we define a test.foo
in application.yml
like you have described:
-- application.yml --
test.foo: ${test.bar:#{null}}
然后,我们在代码中通过 @Value
,如您所说。
Then, we refer to it in code via @Value
, it works as you said.
@Autowired
public A(@Value("test.foo") Object a) {}
但是如果我们直接从环境
获取它,它将是纯字符串:
But If we get it directly from environment
, it will be plain string:
env.getProperty("test.foo")
更多
因此,是否起作用取决于您如何使用它。在提供更多信息之前,我无法提供更多帮助。希望后面的相关帖子可能会对您有所帮助。
More
So, whether it is work or not depends on how did you use it. I can't provide more help before more info. Hope following related post may help.
- Spring EL tutorial
- Spring Boot: customize environment
这篇关于如何在Spring Boot中在application.yml中定义默认的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!