Validating @ConfigurationProperties with Java & Kotlin

March 21, 2019

@ConfigurationProperties annotation is a great way to provide type safe configuration in Spring Boot applications. Classes with this annotation can take configuration from application.(properties|yaml), environment variables or even command line parameters.

How can we know that the values that application expect are passed and that are passed with correct values? We can use good old bean validation for that.

The first step is to make sure you have Hibernate Validator on the classpath. It comes by default with spring-boot-starter-web. If you don’t use it you can just add spring-boot-starter-validation to dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Next, the class we want to validate needs to be annotated with @Validated.

@ConfigurationProperties("some")
@Validated
class SomeProperties {
    ...
}

Once it’s there we can use annotations like @NotNull, @NotBlank etc or create custom ones to make Spring validate values on application startup.

@ConfigurationProperties("some")
@Validated
class SomeProperties {
    @NotBlank
    private String domain;
}

In Kotlin syntax is a bit clumsy since we need to instruct Kotlin to put the annotation on the field:

@ConfigurationProperties("some")
@Validated
data class SomeProperties(@field:NotBlank var domain: String = "")

If any of the validation rules is violated, Spring prints out to the console self explanatory message about the error:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'some' to com.example.demo.SomeProperties failed:

    Property: some.domain
    Value: 
    Origin: class path resource [application.properties]:2:0
    Reason: must not be blank

Do yourself a favor, avoid unexpected bugs, NullPointerExceptions and start validating your @ConfigurationProperties today!