Return to site

🍃📗 PROPERTY PRECEDENCE (SIMPLIFIED)

· spring,springboot,programmmer,java

When your app reads the same property key from multiple places, which value wins? 🤔

Spring Boot has a precedence hierarchy — knowing it saves you from hours of “why is this value not taken into account?!”

🔸 TL;DR

▪️ Spring Boot merges many property sources (devtools, test config, CLI args, env vars, YAML, etc.) into one Environment 🌍

▪️ Higher in the list = stronger override. If the same key appears in multiple places, the one higher wins. 🏆

▪️ Use “strong” sources (like CLI or test annotations) for experiments/tests, and “weaker” ones (like application.yml) for defaults.

🔸 PROPERTY SOURCES FROM STRONGEST TO WEAKEST 💪➡️🧱

(From highest precedence to lowest 👇)

▪️ Devtools settings

For local dev tweaks 🧑‍💻. Super handy when you want to override config just in your dev environment.

▪️ @TestPropertySource and properties on @SpringBootTest

Test-specific overrides 🧪. Perfect for mocking URLs, credentials, or feature flags in integration tests.

▪️ Command-line arguments (--server.port=8081)

Great for changing behavior at deploy/runtime without touching code or config files 🚀.

▪️ SPRING_APPLICATION_JSON (inline JSON)

A single JSON blob (env var or system prop) that can centralize configuration, especially in containerized environments 📦.

▪️ ServletConfig / ServletContext params

Legacy-style servlet container parameters, still supported for older stacks 🌐.

▪️ JNDI java:comp/env

Typical in traditional app servers (Tomcat, WebLogic, etc.) where config is provided by the container 🏢.

▪️ JVM system properties (-Dspring.profiles.active=prod)

Classic Java way to pass configuration at startup ☕.

▪️ OS environment variables (SPRING_PROFILES_ACTIVE=prod)

The cloud-native favorite 🌩️. Ideal for 12-factor apps and secrets/values injected by the platform.

▪️ Profile-specific application properties

Files like application-dev.yml, application-prod.yml that fine-tune behavior per environment 🌱➡️🌳.

▪️ Application properties/YAML (application.properties / application.yml)

Your main default configuration home 🏠. Most app settings live here.

▪️ @PropertySource files

Extra external property files loaded via annotations, often for legacy or module-specific config 📁.

▪️ SpringApplication.setDefaultProperties(...)

Global fallback defaults defined in code. Used when no other source provides a value 🪫.

🔸 TAKEAWAYS

▪️ Define defaults in application.yml, env-specific values in profile files, and ops overrides via env vars / CLI args.

▪️ For tests, prefer @TestPropertySource or properties on @SpringBootTest instead of touching real config files 🧪.

▪️ In production, avoid sprinkling values everywhere — pick 1–2 main sources (e.g., YAML + env vars) for clarity.

#SpringBoot #Java #book #Spring #certification

Go further with Java certification:

Java👇

Spring👇

SpringBook👇