Spring Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


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

That's what we're going to be focusing on in this article – how to specify a default value for the @Value Spring annotation. For a more detailed quick guide on @Value, see the article here.

2. 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, then stringWithDefaultValue will be set to the default value of “my default value”.

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

private String stringWithBlankDefaultValue;

3. Primitives

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

private boolean booleanWithDefaultValue;
private int intWithDefaultValue;

If we wanted to, we could use primitive wrappers instead by changing the types to Boolean and Integer.

4. Arrays

We can also inject a comma-separated list of values into an array:

private String[] stringArrayWithDefaults;

private int[] intArrayWithDefaults;

In the first example above, the values “one”, “two”, and “three” are injected as defaults into stringArrayWithDefaults.

In the second example, the values 1, 2, and 3 are injected as defaults into intArrayWithDefaults.

5. 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;

6. Conclusion

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.

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

Spring bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

newest oldest most voted
Notify of
Juan M

Nice article, btw, I found a typo in the second block of code:

private String stringWithBlankDefaultValue;

At the end of @Value expression, there are a missing a bracket

Grzegorz Piwowarek

Thanks, we will fix that soon 🙂

Comments are closed on this article!