springboot设置默认值,如何在Spring Boot中在application.yml中定义默认的空值

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}}

but it doesn't work.

If the value of test.bar is not defined, set test.foo to null (default value)

I already have spring-el in my dependencies. I don't want to use PropertyPlaceholderConfigurer.setNullValue

It's seem to work in @Value but not in application.yml (see http://farenda.com/spring/spring-inject-null-value/)

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

Thanks

解决方案

@Value

From the document, we can see:

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

It is actually three phases here:

Spring get the annotation string -- AutowiredAnnotationBeanPostProcessor

Spring get property value by the annotation meta data -- Environmen

Spring interpret the property value -- ExpressionParser

User Case

If we define a test.foo in application.yml like you have described:

-- application.yml --

test.foo: ${test.bar:#{null}}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值