Examples of Validating YAML or Properties file configurations using @ConfigurationProperties in Spring Boot.
Tutorial Contents
Overview
Spring Boot @ConfigurationProperties annotation helps map YAML or properties file configurations into a properties class, a plain java bean. This tutorial provides examples of setting up validations on the application-level properties and configurations. The validations help the application fail fast when a necessary configuration is incorrect or absent.
The good news is that Spring Boot @ConfigurationProperties supports Java Bean validation specification – JSR-303 (doc).
If you want to learn more about the @ConfigurationProperties annotation, we recommend reading – Using @ConfigurationProperties in Spring Boot.
Validating Application Properties
The application YAML and Properties files contain the application-level configurations and variables. Thus it is crucial to validate the Configuration Properties Bean and throw an error if something is incorrect. Adding field validations safeguards our applications from unwanted configurations.
Let’s add spring-boot-starter-validation dependency to our application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Code language: HTML, XML (xml)
Doing so, Spring Boot enables Hibernate Bean validations that are based on the ‘javax.validation api‘.
Define @ConfigurationProperties Validations
The following snippet shows a sample ‘application.yaml‘ file from a Spring Boot application. This YAML contains configuration about an external server connection.
Sample application.yaml file.
connection:
host: 192.0.2.1
port: 8181
timeout: 30000
notify: support@example.com
error-file: logs/error.log
Code language: YAML (yaml)
Alternatively, we may have an equivalent properties file.
Let’s create a @ConfigurationProperties class to load the configurations.
@Validated
@Configuration
@ConfigurationProperties(prefix = "connection")
public class ValidatedProperties {
}
Code language: Java (java)
Note that we have added @Validated annotation on top of the class.
To validate that the host property is not null or blank, we will add @NotBlank annotation on the respective field.
@NotBlank
private String host;
Code language: Java (java)
Similarly, we want the port number to be a valid port. Thus, we will use @Min and @Max annotations to provide a range of valid port numbers.
@Min(1025)
@Max(65536)
private int port;
Code language: Java (java)
The timeout value must be a valid positive number. Thus, we have used @PositiveOrZero annotation to ensure the timeout is not a negative number.
@PositiveOrZero
private long timeout;
Code language: Java (java)
The YAML configuration provides an email address to which the error notifications are sent. To ensure that the given email address is valid, we will add @Email annotation.
@Email
private String notify;
Code language: Java (java)
Lastly, we want to ensure that the log file name must end with the ‘.log‘ extension. To do so, we can write a regular expression and use @Pattern annotation with the regexp property.
@Pattern(regexp = "([^\\s]+(\\.(?i)(log))$)")
private String errorFile;
Code language: Java (java)
Run and Verify
Example of @ConfigurationProperties Validations Fail
First, we will run our application with invalid configurations. The following application YAML file shows a group of connection properties. However, based on the validation we added, all fields are invalid.
An invalid Application YAML file
connection:
port: 123
timeout: -13000
notify: supportexample.com
error-file: logs/error.txt
Code language: YAML (yaml)
As it is expected, the application fails to start.
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'connection' to com.amitph.spring.properties.validated.ValidatedProperties$$EnhancerBySpringCGLIB$$67a9fba0 failed:
Property: connection.port
Value: 123
Origin: class path resource [application.yml] - 62:9
Reason: must be greater than or equal to 1025
Property: connection.notify
Value: supportexample.com
Origin: class path resource [application.yml] - 64:11
Reason: must be a well-formed email address
Property: connection.timeout
Value: -13000
Origin: class path resource [application.yml] - 63:12
Reason: must be greater than or equal to 0
Property: connection.errorFile
Value: logs/error.txt
Origin: class path resource [application.yml] - 65:13
Reason: must match "([^\s]+(\.(?i)(log))$)"
Property: connection.host
Value: null
Reason: must not be blank
Action:
Update your application's configuration
Code language: plaintext (plaintext)
When the @ConfigurationProperties validations fail, Spring provides a detailed summary of what went wrong.
Example of @ConfigurationProperties Validations Pass
Lastly, let’s start our application with a valid set of configurations.
connection:
host: 192.0.2.1
port: 8181
timeout: 30000
notify: supportexample.com
error-file: logs/error.log
Code language: YAML (yaml)
We will print the application properties instance upon startup.
* Validated Properties
host: 192.0.2.1
port: 8181
timeout: 30000
notify: support@example.com
errorFile: logs/error.log
Code language: plaintext (plaintext)
The output shows that the application starts up and all the properties are correctly loaded.
Summary
This quick tutorial covered examples of Validating Spring Boot Application Properties or YAML configurations. Spring Boot @ConfigurationProperties support java validation specification (JSR 303), and we can easily plug in the validation using annotations.
We created a Spring Boot @ConfigurationProperties class and added some basic validations like @NotBlank, @Min, @Max, @PositiveOrZero, and @Email. We have also seen an example of adding custom validations using Java Regular Expression with the @Pattern annotation. Spring Boot provides detailed error messages when one or more fields fail the validation.
You can refer to our GitHub Repository for the complete source code of the examples used in this tutorial.
Further Reading:
- Using @ConfigurationProperties in Spring Boot
- YAML to Java List of Objects in Spring Boot
- YAML to Map with Spring Boot
- Reading Nested Properties in Spring Boot