Sub topic 1
Why Spring Boot Externalizes Configuration
Prerequisites
This chapter assumes you can:
- Read and write basic Java, including classes and records.
- Build and run a simple Spring Boot application with Maven or Gradle.
- Explain what a Spring bean is and how dependency injection supplies one.
- Read YAML or
.propertiessyntax.
Later chapters cover each mechanism in detail. This chapter explains the reasoning behind them and gives you a working model to build on.
The problem: values that change between environments
An application rarely runs in only one place. The same code runs on your laptop, in a test pipeline, in staging, and in production. Some values must differ in each place:
- Database URLs and credentials.
- Hostnames and ports of other services.
- Feature switches and timeouts.
- Log levels.
If you write these values into Java source, you must edit the code and rebuild to change them. You then have several slightly different builds, and you can no longer say that what you tested is what you deployed. A hard-coded password also ends up in version control, where anyone with repository access can read it.
Externalized configuration solves this. The compiled application holds the logic and sensible defaults. The values that vary live outside the compiled code and are supplied when the application starts.
What "externalized" means in Spring Boot
Spring Boot builds one artifact, usually a single jar. At startup it collects key-value pairs from several places and merges them into one view called the Environment. Your code asks the Environment for values and never needs to know where a value came from.
Each key is a dotted name such as app.mail.host or server.port. Each value is text that Spring converts to the type you need, such as int, Duration, or boolean.
This gives you three properties:
- One build, many environments. The jar is identical everywhere. Only the supplied values change.
- Layering. Defaults are packaged in the jar. Other sources can override them without editing it.
- Uniform access. A value from a file, an environment variable, or the command line is read the same way.
Where Spring Boot reads configuration
Boot reads many sources. These are the ones you will use most often, from the broadest to the most specific:
| Source | Typical use |
|---|---|
| `application.properties` or `application.yaml` inside the jar | Defaults that suit local development |
| Profile-specific files such as `application-prod.yaml` | Values that apply only to one environment |
| Config files next to the jar or in a config directory | Per-server settings added at deployment |
| OS environment variables | Container and cloud platform settings, secrets |
| Command-line arguments | One-off overrides when launching |
| Test annotations such as `@SpringBootTest(properties = ...)` | Overrides inside a test |
When the same key appears in more than one source, Boot picks one value according to a fixed order. The general rule is that sources closer to the running process, such as command-line arguments, beat sources packaged in the jar. The exact order is the subject of a later chapter. For now, remember that the order exists and is deterministic.
A first example
This application.yaml holds defaults for local development. It lives in src/main/resources.
app:
mail:
host: localhost
port: 1025
sender: [email protected]
retry-attempts: 3A small component reads one of these values. It uses @Value, which injects a single property into a constructor parameter. The class must sit in the same package as your @SpringBootApplication class, or in a sub-package, so component scanning finds it.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
class MailHostPrinter implements CommandLineRunner {
private final String host;
MailHostPrinter(@Value("${app.mail.host}") String host) {
this.host = host;
}
@Override
public void run(String... args) {
System.out.println("Mail host: " + host);
}
}Start the application with no extra input and it prints Mail host: localhost. Now supply the same key from outside, without touching the jar:
# Default from application.yaml
java -jar app.jar
# Command-line argument overrides the packaged default
java -jar app.jar --app.mail.host=smtp.example.com
# Environment variable overrides it too
APP_MAIL_HOST=smtp.internal.example java -jar app.jarThe jar and the Java code are unchanged in all three runs, yet the output differs. Notice that the environment variable APP_MAIL_HOST maps onto the property app.mail.host. Boot's relaxed binding makes this mapping possible. Operating systems do not allow dots in environment variable names, so Boot accepts the upper-case, underscore form.
How the pieces fit
The diagram shows the flow. Several sources feed one merged Environment. Your beans read from it and never read the sources directly.
This indirection is the core design decision. Because beans depend only on the Environment, you can add, remove, or reorder sources without changing application code. A test can inject a value, and a platform can supply a secret, using the same keys.
What belongs in configuration
Not every constant should be externalized. A useful test is to ask whether the value could reasonably differ between two deployments of the same version.
- Externalize: endpoints, credentials, pool sizes, timeouts, feature flags, and anything an operator may need to change in an emergency.
- Keep in code: business rules that define correct behavior, such as a tax calculation formula, and values that never change between environments.
Providing defaults in the packaged file is good practice. The application then starts on a developer machine with no setup, and production overrides only what differs. Defaults should be safe. A default that points at a real production database is a hazard.
Common errors
These mistakes appear often when teams first adopt externalized configuration.
- Unresolved placeholder. If
app.mail.hostis defined nowhere, the@Value("${app.mail.host}")injection fails at startup with anIllegalArgumentExceptionabout a placeholder that cannot be resolved. The application stops. You can supply a fallback in the placeholder, as in${app.mail.host:localhost}, but a silent fallback can hide a missing production setting. Prefer failing fast for values that must be set. - Editing the wrong file. Changes to
src/main/resources/application.yamlreach a running jar only after a rebuild. Changes to files intarget/classesorbuild/resourcesare overwritten by the next build. To change a deployed value, use an external source instead. - Surprising winners. A stale environment variable in your shell can silently beat the value in your file. When a setting seems ignored, suspect a higher-priority source before suspecting the file.
- Secrets committed to version control. Putting a password in
application.yamlmakes it part of the repository history, and deleting it later does not remove it from history. A later chapter covers secret handling. - Whitespace and indentation in YAML. A wrongly indented line produces a different key than you intended, for example
app.mail-hostinstead ofapp.mail.host. Boot does not report this as an error. The value is simply never found.
Summary of the working model
- Boot builds one jar and merges key-value pairs from many sources into an
Environment. - Keys are dotted names, and values are converted to the type your code asks for.
- A fixed precedence order decides which source wins when keys collide.
- Defaults ship in the jar, and each deployment overrides only what it needs.
- Beans read from the
Environment, so they are unaware of where a value originated.
Exercise
Your application reads app.mail.host and the packaged application.yaml sets it to localhost. In production you start the jar with the environment variable APP_MAIL_HOST=smtp.example.com and no other changes. Which host does the application use, and why does the jar not need to be rebuilt?
Show answer
It uses smtp.example.com. The environment variable is a higher-priority source than the file packaged inside the jar, and relaxed binding maps APP_MAIL_HOST to the property app.mail.host. Because all sources merge into the Environment at startup, the override is applied at launch time, so the same jar works unchanged.
Exercise
A teammate puts the production database password in application.yaml and later deletes it in a follow-up commit. Is the secret now safe? Name one better place for it.
Show answer
No. The password remains in the repository history and can be recovered from earlier commits, so it should be treated as compromised and rotated. A better place is an environment variable or a secrets manager that supplies the value at deployment time, outside version control.