Spring Boot version: 2.7.2

When writing tests using the @SpringBootTest annotation, properties don't correctly load into configuration classes which use @ConstructorBinding and @ConfigurationProperties. However, they do load correctly when they are individually marked with @Value.

Example test file:

@SpringBootTest(classes = [ConfigurationClass::class])
class TestClass() {
...
}

Configuration class which does NOT load properties successfully:

@ConstructorBinding
@ConfigurationProperties(prefix = "some.properties")
data class ConfigurationClass(
    val blah: String = ""
)

Configuration class which does load properties successfully:

@Configuration
data class ConfigurationClass(
    @Value("\${some.properties.blah}")
    val blah: String = ""
)

Comment From: wilkinsona

By referencing ConfigurationClass in classes of @SpringBootTest, you're registering it as a Spring-managed component that will be created using standard dependency injection rather than configuration property binding. You should use @EnableConfigurationProperties or @ConfigurationPropertiesScan instead. Please see the documentation on @ConstructorBinding for further details, particularly this note:

To use constructor binding the class must be enabled using @EnableConfigurationProperties or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example @Component beans, beans created by using @Bean methods or beans loaded by using @Import)

If you have any further questions, please follow up on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.

Comment From: aconnoy

Ahh I see, my mistake 😅. Thank you for the help!!