1.概览

Spring 的 @Vaule 注解提供了一种便捷的办法能够让属性值注入到组件中,当属性值不存在的时候提供一个默认值也是十分好用的

这就是咱们这篇文章所专一的,如何给 @Vaule 注解指定一个默认值。对于更多的对于 @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;

6.总结

在这篇文章中,咱们钻研了如何为应用Spring的@Value正文注入的属性设置默认值。

像平常一样,本文中应用的所有代码示例都能够在GitHub我的项目中找到。