Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 904
khong07 Avatar asked Dec 02 '15 11:12

khong07


People also ask

Can null be a default value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

How do you access a value defined in the application Yml file in spring boot?

To read from the application. yml or property file : The easiest way to read a value from the property file or yml is to use the spring @value annotation.

What do you understand by default value and null value?

null means that some column is empty/has no value, while default value gives a column some value when we don't set it directly in query.


1 Answers

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

  • Spring EL tutorial
  • Spring Boot: customize environment
like image 82
Tony Avatar answered Sep 19 '22 12:09

Tony