Properties stores string keys and values; application precedence is determined by the order and policy used to combine sources.
Java Properties precedence: merge sources deliberately
This complete Java 8 program has a checked output. Compile it as the named public class, then run it without additional libraries.
Choose which source wins
This fixture starts with packaged defaults and then overlays a local override. The second putAll wins on duplicate keys. java.util.Properties does not impose a standard deployment precedence between files, environment variables and command-line flags for an application.
A caller should define and test the priority of each accepted source. In a Spring application the framework has its own property-source ordering, covered by Spring profile and property precedence. Do not copy this fixture's order into Spring and assume it overrides Boot's behavior.
Validate before starting work
The program parses the merged timeout as a number and rejects a nonpositive value. Real services also need bounds, units and a policy for unknown keys. Never print a secret just to prove precedence; this example uses a harmless timeout setting.
Working program
import java.util.Properties;
public class ImportTimeoutConfiguration {
public static void main(String[] args) {
Properties defaults = new Properties();
defaults.setProperty("import.timeout.seconds", "8");
Properties local = new Properties();
local.setProperty("import.timeout.seconds", "12");
Properties effective = new Properties();
effective.putAll(defaults);
effective.putAll(local);
int seconds = Integer.parseInt(effective.getProperty("import.timeout.seconds"));
if (seconds <= 0 || seconds > 60) throw new IllegalArgumentException("timeout range");
System.out.println("timeout=" + seconds);
}
}Output
timeout=12Costs and boundaries
Merging n entries takes O(n) expected map work and retains a new map of O(n) references and strings. Parsing and validation should happen once at startup, not on every request.
Common Mistakes
- Do not assume Properties chooses file or environment precedence for you.
- Do not treat a parsed integer as a validated duration.
- Do not log effective secret values during diagnostics.
Read next
Java classes and objects, Spring Boot profiles and property precedence: test the selected environment, Spring Boot configuration properties: bind values and reject bad startup input.
