5

I'm having trouble setting null as a property value.

This is how the value is defined in YAML file:

my-property: null

This is how I inject it in code:

@Value("${my-property}")
private String myProperty;

For some reason, Spring keeps injecting an empty string ("") instead of null. Am I missing something or is this an error in Spring?

Jardo
  • 1,939
  • 2
  • 25
  • 45
  • Thats simply because 'null' in YAML file undestood as 'null' string, not null value. To get what you want just remove value at all and then use null as default value in EL: @Value("${my-property:null}") – Alex Chernyshev Nov 23 '20 at 19:33

3 Answers3

2

You can't, but this is not because YAML. YAML supports null as per:

Empty field in yaml

This is because of a Spring processor class, which turns "null" values into empty strings, see here:

https://github.com/spring-projects/spring-framework/issues/19986

breakline
  • 5,776
  • 8
  • 45
  • 84
0

Try to use instead of $ use this #. Or try this @Value("${<my-property>}")

Co ti
  • 124
  • 2
  • 13
0

I had a similar use case, and had to go through quite a bit of trial and error.

The following two-step solution worked for me

  1. Don't define my-property in the YAML file. This way Spring cannot (annoyingly) inject a stringified value like "" or "~" or "null", and will be forced to look for a default value.

  2. Use #{null} as the default value. This is an SpEL expression that evaluates to null.

In your example, it will be

@Value("${my-property:#{null}}")
private String myProperty;

Be careful not to mess up with the curly brackets.

Turzo
  • 490
  • 1
  • 5
  • 14