Type‑Safe Spring Boot Configuration with @ConfigurationProperties, Constructor Binding, and Validation
Learn how to bind structured YAML properties to immutable Java records, validate them at startup, and switch values per profile without code changes.
05 Jun 2026, 20:51 UTC

Use constructor‑bound @ConfigurationProperties for immutable, validated config
Spring Boot 2.2+ makes constructor binding the default for @ConfigurationProperties. Declare a single constructor whose parameter names match the property keys, add Jakarta Bean Validation annotations, and the context will fail to start if required values are missing or out of range. This replaces scattered @Value injections and gives you a single, type‑safe bean you can inject anywhere.
Worked example: a service‑level configuration
1. Define the properties in application.yml
app:
service:
name: "order-service"
port: 8081
timeout-ms: 5000
retries: 3
allowed-origins:
- "https://app.example.com"
- "https://admin.example.com"
2. Create the configuration class (record for immutability)
package com.example.config;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import java.util.List;
@ConfigurationProperties(prefix = "app.service")
@Validated
public record ServiceProperties(
@NotBlank String name,
@Min(1) int port,
@Min(0) long timeoutMs,
@Min(0) int retries,
@NotNull @NotEmpty List<@NotBlank String> allowedOrigins
) {}
The record’s canonical constructor satisfies the single‑constructor requirement. Parameter names (name, port, …) must be preserved at runtime; enable the -parameters compiler flag (see step 4).
3. Enable the configuration processor for IDE completion
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
After a build, target/classes/META-INF/spring-configuration-metadata.json contains the property documentation that IDEs use for autocomplete in application.yml.
4. Preserve parameter names in the build
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
Without <parameters>true</parameters> the constructor parameters are compiled without names, causing Spring to fall back to setter binding (which fails for records) or to ignore the properties entirely.
5. Profile‑specific overrides
Create application-dev.yml and application-prod.yml next to the base file. Only the values that differ need to be repeated.
# application-dev.yml
app:
service:
port: 8082
timeout-ms: 10000
# application-prod.yml
app:
service:
port: 443
retries: 5
Activate a profile at startup:
# Linux/macOS
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
# Windows PowerShell
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
The same ServiceProperties bean will receive the profile‑specific values without any code change.
6. Verify the binding and validation
- Compile and inspect metadata – run
./mvnw compileand opentarget/classes/META-INF/spring-configuration-metadata.json. You should see entries forapp.service.name,app.service.port, etc. - Start with an invalid value – temporarily change
port: -1inapplication.ymland run the app. The context fails to start with aConstraintViolationExceptionreferencingport must be greater than or equal to 1. - Confirm profile override – start with
--spring.profiles.active=devand log the bean:
The output should show@Component public class ConfigPrinter implements CommandLineRunner { private final ServiceProperties props; public ConfigPrinter(ServiceProperties props) { this.props = props; } @Override public void run(String... args) { System.out.println("Bound config: " + props); } }port=8082andtimeoutMs=10000.
Limits and common mistakes
| Issue | Why it happens | Mitigation |
|---|---|---|
| Unknown properties are silently ignored | By default Spring does not reject extra keys in the YAML. | Set spring.config.import=optional:classpath:application.yml and enable @ConfigurationPropertiesBinding with ignoreUnknownFields=false (Spring Boot 3.2+) or write a custom PropertySource validator. |
Missing -parameters flag |
Constructor parameter names are stripped at compile time. | Always configure maven-compiler-plugin (or Gradle tasks.withType(JavaCompile) { options.compilerArgs << '-parameters' }). |
Mixing @Value and @ConfigurationProperties for the same prefix |
Creates two binding paths; overrides become unpredictable. | Pick one style per prefix. Prefer @ConfigurationProperties for structured config. |
| Validation package mismatch across Spring Boot versions | Boot 2.x uses javax.validation, Boot 3.x uses jakarta.validation. |
Update imports when migrating; keep the spring-boot-starter-validation dependency aligned with the Boot version. |
| Relaxed binding quirks with collections | Environment variables map APP_SERVICE_ALLOWED_ORIGINS_0 to the first list element, but YAML lists bind naturally. |
Prefer YAML for nested collections; if you must use env vars, follow the _ naming convention and test the binding. |
| Records cannot have default values | All components must be supplied via the constructor. | Provide defaults in the YAML or use a regular class with a no‑arg constructor and setters if defaults are required. |
Quick checklist before committing
maven-compiler-pluginhas<parameters>true</parameters>.spring-boot-configuration-processoris present (optional scope).- Configuration class is annotated with
@ConfigurationPropertiesand@Validated. - All fields have appropriate Jakarta Bean Validation constraints.
- Profile‑specific YAML files exist for each environment.
- Run
./mvnw compileand verifyspring-configuration-metadata.jsoncontains your prefixes. - Start the app with an invalid value to confirm fast‑fail validation.
How to verify the result in CI
Add a test that loads the Spring context with a deliberately bad property and asserts a ConstraintViolationException:
@SpringBootTest(properties = "app.service.port=-5")
class ServicePropertiesValidationTest {
@Autowired ApplicationContext ctx;
@Test void invalidPortFailsStartup() {
assertThrows(ConstraintViolationException.class, () -> ctx.getBean(ServiceProperties.class));
}
}
Run the test in your pipeline (./mvnw test) to guarantee that validation stays active after refactors.
Summary
Constructor‑bound @ConfigurationProperties gives you a single, immutable, validated configuration bean. Combine it with the configuration processor for IDE support, profile‑specific YAML for environment differences, and Jakarta Bean Validation for fast‑fail startup. The only required build‑time step is preserving parameter names; everything else is declarative and checked at context initialization.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.