如何将@Value定义为可选 [英] How to define @Value as optional

查看:206
本文介绍了如何将@Value定义为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring bean中具有以下内容:

I have the following in a Spring bean:

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

该值已正确注入.但是,该变量必须是可选的,它作为命令行参数传递(然后使用 SimpleCommandLinePropertySource 添加到Spring上下文),并且该参数不会总是存在.

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

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

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.

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

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

谢谢

推荐答案

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

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

假设不需要"是指null然后...

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

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

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

您不仅可以将纯字符串用作默认值.您可以使用 SPEL 表达式和简单的SPEL表达式来返回null是:

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

这篇关于如何将@Value定义为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆