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?
Try to use instead of $
use this #
. Or try this @Value("${<my-property>}")
You can't, but this is not because YAML. YAML supports null as per:
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
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.