IDE Support for Spring Boot's @ConfigurationProperties

August 10, 2019

With the @Value annotation provided by the Spring core container we can access properties through Spring's Environment abstraction. Spring Boot comes with an alternative that is preferable in many cases: @ConfigurationProperties allows binding properties to structured objects as shown in the listing below and as described in the Spring Boot reference.

@Validated
@ConfigurationProperties(prefix = "sample")
public class SampleProperties {
    
    @NotNull
    @Pattern(regexp = "\\d{3}-\\w+")
    private String nickname;
    
    @NotNull
    private Currency defaultCurrency;
    
    @Min(0)
    @Max(5000)
    private BigDecimal balance;
    
}

Note the usage of the @Validated annotation in combination with the javax.validation.* annotations on the fields. On top of typesafe bindings we can also add bean validation to detect misconfiguration at application start. For this to work, an implementation of JSR 303 must be available - e.g. through a dependency on spring-boot-starter-validation.

We then need to register our SampleProperties class with the @EnableConfigurationProperties annotation on a configuration class:

@Configuration
@EnableConfigurationProperties(SampleProperties.class)
public class MyConfiguration {
}

With this minimal setup we now have property binding with effortless validation.
The IDE support for this setup could be improved though. In IntelliJ the application.yml file now looks like this:

IntelliJ complains that it cannot resolve a configuration property and there is no navigation support between the custom properties in the application.yml file and the members in our SampleProperties class. This is because no metadata is generated for SampleProperties. We need to add the spring-boot-configuration-processor dependency in the module and rebuild the project as outlined in the Spring Boot reference.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

Thanks to the processor we can now benefit from improved IDE support.

That's it. Happy coding :)

About the author: Rocco Schulz

Rocco loves clean air in the mountains and clean code in projects. He is interested in a multitude of sports activities, machine learning and various software engineering topics.

Comments
Join us