spring 如何将@Value 定义为可选

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23348061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:41:01  来源:igfitidea点击:

How to define @Value as optional

springspring-bean

提问by user1052610

I have the following in a Spring bean:

我在 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.

该值已正确注入。但是,该变量需要是可选的,它作为命令行参数传入(然后使用SimpleCommandLinePropertySource添加到 Spring 上下文中),并且此参数不会始终存在。

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.

但在每种情况下,即使存在实际值,也会注入冒号后的默认参数 - 这似乎覆盖了 Spring 应该注入的内容。

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

指定不需要@Value的正确方法是什么?

Thanks

谢谢

回答by Andy Brown

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

指定不需要@Value 的正确方法是什么?

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

假设“不需要”你的意思是null......

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

您已经正确地注意到可以在:字符右侧提供默认值。你的例子是@Value("${myValue:DEFAULT}").

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

您不仅限于将纯字符串作为默认值。您可以使用SPEL表达式,返回的简单 SPEL 表达式null为:

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

回答by alonso_50

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

如果您使用的是 Java 8,则可以利用它的java.util.Optional类。您只需按照以下方式声明变量:

@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!

希望能帮助到你!