How to define @Value as optional

情到浓时终转凉″ 提交于 2019-11-28 16:55:56

问题


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


回答1:


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}}")



回答2:


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!



来源:https://stackoverflow.com/questions/23348061/how-to-define-value-as-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!