1. Overview
1.概述
Spring’s @Value annotation provides a convenient way to inject property values into components. It’s also quite useful to provide sensible defaults for cases where a property may not be present.
Spring的@Value注解提供了一种将属性值注入组件的便捷方式。它对于为可能不存在属性的情况提供合理的默认值也非常有用。
That’s what we’re going to be focusing on in this tutorial — how to specify a default value for the @Value Spring annotation.
这就是我们在本教程中要关注的内容–如何为@Value Spring注解指定默认值。
For a more detailed quick guide on @Value, see the article here.
关于@Value的更详细的快速指南,请参阅文章这里。
2. String Defaults
2.字符串的默认值
Let’s look at the basic syntax for setting a default value for a String property:
让我们看一下为String属性设置默认值的基本语法。
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
If some.key cannot be resolved, stringWithDefaultValue will be set to the default value of my default value.
如果some.key不能被解决,stringWithDefaultValue将被设置为my default value的默认值。
Similarly, we can set a zero-length String as the default value:
同样地,我们可以设置一个零长度的String作为默认值。
@Value("${some.key:})"
private String stringWithBlankDefaultValue;
3. Primitives
3.基元
To set a default value for primitive types such as boolean and int, we use the literal value:
为了给原始类型如boolean和int设置一个默认值,我们使用字面值。
@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
@Value("${some.key:42}")
private int intWithDefaultValue;
If we wanted to, we could use primitive wrappers instead by changing the types to Boolean and Integer.
如果我们想,我们可以通过将类型改为Boolean和Integer来使用原始包装器。
4. Arrays
4.数组
We can also inject a comma separated list of values into an array:
我们也可以将一个逗号分隔的数值列表注入一个数组中。
@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;
In the first example above, the values one, two and three are injected as defaults into stringArrayWithDefaults.
在上面的第一个例子中,值one、two和three被作为默认值注入stringArrayWithDefaults。
In the second example, the values 1, 2 and 3 are injected as defaults into intArrayWithDefaults.
在第二个例子中,值1、2和3被作为默认值注入intArrayWithDefaults。
5. Using SpEL
5.使用SpEL
We can also use Spring Expression Language (SpEL) to specify an expression and a default.
我们还可以使用Spring表达式语言(SpEL)来指定一个表达式和一个默认值。
In the example below, we expect some.system.key to be set as a system property, and if it is not set, we want to use my default system property value as a default:
在下面的例子中,我们希望some.system.key被设置为系统属性,如果它没有被设置,我们希望使用我的默认系统属性值作为默认。
@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;
6. Conclusion
6.结论
In this quick article, we looked at how we can set a default value for a property whose value we would like to have injected using Spring’s @Value annotation.
在这篇快速文章中,我们看了如何为一个属性设置默认值,我们希望使用Spring的@Value注解来注入其值。
As usual, all the code samples used in this article can found in the GitHub project.
像往常一样,本文中使用的所有代码样本都可以在GitHub项目中找到。