'How to define default null value in application.yml in Spring Boot

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



Solution 1:[1]

@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.

Solution 2:[2]

Try to use:

-- application.yml --
test.foo: ${test.bar:}

Solution 3:[3]

you need to set it like that:

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

Edit: The answer showed ${test.bar:'#{null}'} before, which is not correct.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tony
Solution 2 anisgh
Solution 3 towi