0

Spring – Configurable Default Value for @Value

Spring – Configurable Default Value for @Value that has both a configurable default value and a hard-coded final fallback value. This annotation may be used to inject values into fields in Spring-managed beans.

Requirements

Stuff used in this post.

  • Java 8 (JDK)
  • IntelliJ IDEA Ultimate 2016.3
  • Spring Boot 1.5.6.RELEASE

@Value General Usage

@Value can be applied at the field or constructor/method parameter level.

Hard-coded Default Value

It is possible to assign a field or constructor/method parameters with default value when, e.g., the property from.configuration.file.property.a is not defined.

From these usages, let’s go beyond them!

Instead of just having a hard-coded default value, we’ll have a configurable default value and a hard-coded final fallback default value.

Our application.properties

Initially, our configuration file has the following lines.

One property is “user-defined” and another is “system-defined”.

We use these properties with the @Value annotation:

Notice the expression passed to the @Value annotation.

Testing

We’ll test 3 scenarios: 1) with “user-defined” and “system-defined” properties defined; 2) with only “system-defined” property defined; and finally, 3) with no properties explicitly defined.

Test A

Configuration:

Output:

It outputs the “user-defined” value.

Test B

Configuration:

Output:

It outputs the configurable default value.

Test C

Configuration:

Output:

It outputs the hard-coded final fallback value.

Download the codes

Please download from our GitHub account.

https://github.com/Turreta/4uq0ofsm1rj2xgedpf6b