Contents

Spring @Value默认值

1.概述

Spring 的*@Value*注解提供了一种将属性值注入组件的便捷方式。为可能不存在属性的情况提供合理的默认值也非常有用。

这就是我们将在本教程中关注的内容——如何为*@Value* Spring 注解指定默认值。

有关*@Value*的更详细的快速指南,请参阅此处 的文章。

2. 字符串默认值

让我们看一下为String属性设置默认值的基本语法:

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

如果some.key无法解析,stringWithDefaultValue将设置为* default value 的默认值*。

同样,我们可以设置一个长度为零的字符串作为默认值:

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

3. 基本类型

要为booleanint等基本类型设置默认值,我们使用字面值:

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

如果我们愿意,我们可以通过将类型更改为BooleanInteger来使用基本类型。

4. 数组

我们还可以将逗号分隔的值列表注入数组:

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

在上面的第一个示例中,值onetwo 和three作为默认值注入到stringArrayWithDefaults中。

在第二个示例中,值12 和3作为默认值注入到intArrayWithDefaults中。

5. 使用SpEL

我们还可以使用 Spring 表达式语言 (SpEL) 来指定表达式和默认值。

在下面的示例中,我们希望将 some.system.key设置为系统属性,如果未设置,我们希望使用默认系统属性值 作为默认值:

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