How to define @Value as optional

纵然是瞬间 提交于 2019-11-29 21:09:53

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

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!

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