一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Spring@Value设置默认值如何实现 Spring@Value设置默认值实现代码

时间:2020-09-10 编辑:袖梨 来源:一聚教程网

Spring@Value设置默认值如何实现?本篇文章小编给大家分享一下Spring@Value设置默认值实现代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

1.概览

Spring 的 @Vaule 注解提供了一种便捷的方法可以让属性值注入到组件中,当属性值不存在的时候提供一个默认值也是非常好用的

2.String 默认值

让我们看看对于 String 类型的值,给定一个默认值得基础语法

@Value("${some.key:my default value}")
private String stringWithDefaultValue;

如果 some.key 无法解析,那么 stringWithDefaultValue 的值会被设置为默认值 "my default value".

相似的,我们也可以用如下方法,设置一个空字符串作为默认值

@Value("${some.key:})"
private String stringWithBlankDefaultValue;

3.原始类型

给像 int 或者 boolean 的原始类型赋一个默认值,我们使用文字值:

@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private int intWithDefaultValue;

如果愿意,可以用原始类型的包装类型来代替,例如 Boolean 和 Integer

4.数组

我们可以使用逗号分隔的 list 来用于数组的注入,如下

@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
 
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;

在上面第一个例子, 值为 "one", "two", 和 "three" 的数组将被注入到 stringArrayWithDefaults 中

在上面第二个例子, 值为 1, 2, 和 3 的数组将被注入 intArrayWithDefaults 中

5.使用SpEL表达式

我们也可以使用 Spring Expression Language (SpEL) 去指定一个表达式或者默认值

在下面的例子中,我们期望 some.system.key 被设置为系统值,如果他不存在则我们想用 "my default system property value"

@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;

热门栏目