How to define @Value as optional

SpringSpring Bean

Spring Problem Overview


I have the following in a Spring bean:

@Value("${myValue}")
private String value;

The value is correctly injected. However, the variable needs to be optional, it is passed in as a command line parameter (which is then added to the Spring context using a SimpleCommandLinePropertySource), and this argument will not always exist.

I have tried both the following in order to provide a default value:

@Value("${myValue:}")
@Value("${myValue:DEFAULT}")

but in each case, the default argument after the colon is injected even when there is an actual value - this appears override what Spring should inject.

What is the correct way to specify that @Value is not required?

Thanks

Spring Solutions


Solution 1 - Spring

> What is the correct way to specify that @Value is not required?

Working on the assumption that by 'not required' you mean null then...

You have correctly noted that you can supply a default value to the right of a : character. Your example was @Value("${myValue:DEFAULT}").

You are not limited to plain strings as default values. You can use SPEL expressions, and a simple SPEL expression to return null is:

@Value("${myValue:#{null}}")

Solution 2 - Spring

If you are using Java 8, you can take advantage of its java.util.Optional class. You just have to declare the variable following this way:

@Value("${myValue:#{null}}")
private Optional<String> value;

Then, you can check whether the value is defined or not in a nicer way:

if (value.isPresent()) {
    // do something cool
}

Hope it helps!

Solution 3 - Spring

I guess you are you using multiple declarations?

If so, this is a known issue since 2012, but not fixed, apparently due to both lack of interest and no clean way of fixing it. See https://github.com/spring-projects/spring-framework/issues/14623 for discussion and some ways to work around it. It's explained in an understandable way by http://www.michelschudel.nl/wp/2017/01/25/beware-of-multiple-spring-propertyplaceholderconfigurers-and-default-values/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1052610View Question on Stackoverflow
Solution 1 - SpringAndy BrownView Answer on Stackoverflow
Solution 2 - Springalonso_50View Answer on Stackoverflow
Solution 3 - SpringStefan LView Answer on Stackoverflow