跳至主要内容

[Spring] @Value Defaults

Src: Using Spring @Value with Defaults | Baeldung
Noted: 2023-08-23

Overview

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 — how to specify a default value for the @Value Spring annotation.

String Defaults

Let's look at the basic syntax for setting a default value for a String property:

@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.

Similarly, we can set a zero-length String as the default value:

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

@Value annotation : 後面即為 default value. 沒有給任何值的話並不為 null, 而因不同物件會有不同資料內容. String 的話會是空字串 ""

Primitives

To set a default value for primitive types such as boolean and int, we use the literal value:

@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.

Arrays

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.

Using SpEL

We can also use Spring Expression Language (SpEL) to specify an expression and a default.

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:

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

Conclusion

Spring @Value 裡面的的格式規範類似 YAML, 用 , 區隔陣列元素, 非必要並無須特別加上 "" ... 等. 但若字串中有混雜特殊字元等導致誤判, 可利用 ' 單引號來定義字串.

This article looked at how to set a default value for a property whose value we would like to have injected using Spring's @Value annotation.

As usual, all the code samples used in this article can found in the GitHub project.

See Also