Using Spring @value With Defaults
Using Spring @value With Defaults
// Best Practices
Hi Backend Team,
While declaring config values, pass default values as well, even if you miss in properties application will start. This is
stopping application to start.
Strings:
@Value("${some.key:my default value}")
private String stringWithDefaultValue;
ex:
Similarly, we can set a zero-length String as the default value:
@Value("${some.key:})"
private String stringWithBlankDefaultValue;
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;
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;
1
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:
Ref:
https://www.baeldung.com/spring-value-defaults