External configuration precedence
What you will learn
External configuration allows the same artifact to run with different settings. Bind related options to a typed object and validate them before use; changing deployment values should not require editing domain code.
- Predict precedence among common configuration sources.
- Bind and validate a typed configuration record.
- Explain profile overrides and safe startup failure.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Boot examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Merge synthetic configuration layers
import java.util.*;public class Main { public static void main(String[] args) { var merged = new HashMap<>(Map.of("lab.batch-size", "10")); merged.putAll(Map.of("lab.batch-size", "20")); merged.putAll(Map.of("lab.batch-size", "35")); System.out.println(merged.get("lab.batch-size")); }}Expected output:
35Each putAll replaces the previous value for this key. Real Boot also has origins, relaxed binding, profile activation and more sources.
A practical precedence ladder
For the subset used here, default properties are weaker than config data; OS environment variables override config data, Java system properties override OS environment variables, and command-line properties override both. Tests and other special sources can change the full order. Packaged and external config data have their own ordering: external files can override packaged values, and profile-specific files override corresponding generic files. This is not a complete list; consult the versioned table. @PropertySource is added during refresh and is too late for some early settings such as logging and spring.main.
Typed binding and validation
Use @ConfigurationProperties("lab") to group lab.* keys and @EnableConfigurationProperties to register the record. Single-constructor records support constructor binding; @Validated activates validation with a validation implementation on the classpath. @Min and @Max constrain the int. Missing primitive batchSize falls to zero here and fails @Min; malformed input should fail conversion. The kebab-case key lab.batch-size binds batchSize; the environment variable convention removes dashes (LAB_BATCHSIZE). Avoid silently choosing a fallback for invalid input. Use a typed Duration for time limits when relevant, with explicit units such as 5s.
Profiles and secrets
With the lab profile active, application-lab.properties overrides packaged application.properties. CLI --lab.batch-size=35 wins over both. Use profiles for related behavior, not as a security boundary. Do not print entire Environment or records carrying secrets. Store secret material in approved secret management, restrict access and do not commit it. The lab logs only an allowlisted numeric setting.
Validate before accepting configuration
public class Main { record Settings(int batchSize) { Settings { if (batchSize < 1 || batchSize > 100) throw new IllegalArgumentException("batch size"); } } public static void main(String[] args) { System.out.println(new Settings(1).batchSize()); System.out.println(new Settings(100).batchSize()); try { new Settings(0); } catch (IllegalArgumentException ex) { System.out.println("rejected"); } }}Expected output:
1100rejectedPlain Java validates constructor input; Boot’s binding and Jakarta Validation are separate mechanisms.
Typed settings record
Source-reviewed, NOT RUN. File lab-fixtures/boot-v38/src/main/java/example/bootlab/LabSettings.java; use the companion lab README.
package example.bootlab;
import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.validation.annotation.Validated;
@ConfigurationProperties("lab")@Validatedpublic record LabSettings(@Min(1) @Max(100) int batchSize) {}Predicted behavior: Valid configuration binds a record; 0 or 101 should prevent successful startup.
Validation starter supplies an implementation; the application registers the record.
Base application properties
Source-reviewed, NOT RUN. File lab-fixtures/boot-v38/src/main/resources/application.properties; use the companion lab README.
# Synthetic configuration. Never include credentials here.server.address=127.0.0.1server.port=18080lab.batch-size=10management.endpoints.web.exposure.include=healthmanagement.endpoint.health.show-details=nevermanagement.endpoint.health.show-components=neverspring.jmx.enabled=falselogging.level.root=INFOPredicted behavior: Batch size 10, loopback listener on 18080, health-only HTTP exposure.
Treat overrides as trusted launch inputs; inspect actual binding before sending requests.
Profile override
Source-reviewed, NOT RUN. File lab-fixtures/boot-v38/src/main/resources/application-lab.properties; use the companion lab README.
Predicted behavior: Batch size 20 when the lab profile is active; CLI 35 still wins.
Activate with --spring.profiles.active=lab; keep the loopback flags in the lab README.
Common mistakes
A profile is not access control. A string that parses to an integer may still violate a domain constraint. An environment variable name with an extra underscore is not necessarily the intended relaxed-binding key. Do not dump all properties to debug a single value.
Practice
Write a resolver taking default and optional override strings. Parse the selected value, require 1–100, and print 10 for no override, 35 for override 35, and rejected for invalid 101.
Expected output:
1035rejectedCompare with the manual review criteria.
Official reading: Config. Boot execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
External configuration precedence — knowledge check
Spring Boot configuration and operational reasoning.
Which normally wins in the subset shown?
What enables validation for the settings record?
Which environment name corresponds to lab.batch-size?
What happens to 0 under @Min(1)?
What is a profile useful for?