0

Validate Properties Files At Startup in Spring Boot

Last Updated on

This post is about how to validate Properties files at the application startup using Spring Boot. A .properties file contains lines of string pair. Each string pair consists of a parameter name (called the key), and parameter value. We typically the parameter value. By doing the validation at the moment the application starts, we can reduce the number of errors at run-time that are related to properties files, and the number of validation codes in other areas.

Requirements

This post uses the following.

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

The Properties File To Validate

Let’s say we have this properties file. We want to check the values against some rules.

Validate Against Rules

Modules 1 and 2 have these rules.

  • Parameter timeoutInSeconds must not be null and between 30 and 120 inclusively
  • Parameter allowedGroups must not be null, and have at least 1 but at most 3 groups

When we validate our properties file, the validation fails because module2.timeoutInSecond is out of range and module2.allowedGroups has more than 3 groups.

Module1ConfigBean

This class represents a properties file named something-very-important-config.properties. The prefix module1 ensures that it only looks for property names that start with module1. Also, the @Validated triggers the validation of the class’ properties.

Module2ConfigBean

This class refers to the same properties file but uses prefix module2 to look for property names that start with module2.

Testing

Our main class is simple. It runs Spring Boot and allows it to validates the Properties file at startup.

We get the following errors when we run the application. As expected, the validation fails.

If we correct the parameter values, we get the following output. As expected, the validation works.

Download the codes

The codes are available at Github.

Avatar

Karl San Gabriel

Professional Software Developer