Sub topic 3
Property sources and which value wins
This chapter assumes you can read YAML and .properties files, you have a basic Spring Boot application built with Maven or Gradle, and you know how Spring beans and injection work. Here you learn how Spring Boot decides which value to use when the same key is defined in more than one place.
One key, many sources
Spring Boot does not read configuration from a single place. It builds an Environment, which is an ordered list of property sources. Each source is a named collection of key-value pairs: a config file, the operating system's environment variables, command-line arguments, and so on.
When your code asks for app.mail.port, Spring walks the list from the top. The first source that contains the key supplies the value. Sources lower in the list are never consulted for that key. "Which value wins" therefore means "which source is earliest in the list".
You rarely need to change this list. You do need to know its order so you can predict what a running application sees.
The order, from highest to lowest
Spring Boot documents the order from lowest to highest priority. The table below reverses that, so the winner comes first. It lists the sources you meet most often. The full list also includes devtools settings, JNDI, and servlet init parameters.
| Priority | Source | Typical use |
|---|---|---|
| 1 (highest) | `@TestPropertySource` and `@DynamicPropertySource` on tests | Test-specific values |
| 2 | `properties` attribute of `@SpringBootTest` | Inline test overrides |
| 3 | Command-line arguments (`--key=value`) | One-off overrides at launch |
| 4 | `SPRING_APPLICATION_JSON` | JSON blob in an environment variable or system property |
| 5 | Java system properties (`-Dkey=value`) | JVM-level settings |
| 6 | OS environment variables | Container and cloud deployments |
| 7 | Config data files (`application.properties` or `.yaml`, covered below) | Your main configuration |
| 8 | `@PropertySource` on `@Configuration` classes | Extra `.properties` files |
| 9 (lowest) | Default properties set with `SpringApplication.setDefaultProperties` | Library-style fallbacks |
The random.* values (random.int, random.uuid) sit between environment variables and config files. Most applications never notice.
The pattern is that the closer a source is to launch time or to the test, the higher its priority. Files packaged in the jar are the most general, so they lose to almost everything.
The order inside config data files
Config data files are the application.properties and application.yaml files from the chapter before this one. They are not a single level. Spring Boot loads them from several locations and layers them in this order, with later entries overriding earlier ones:
- Files packaged inside the jar (classpath root, then
/configon the classpath). - Profile-specific files inside the jar, such as
application-prod.yaml. - Files outside the jar, in the working directory and in its
./config/folder. - Profile-specific files outside the jar.
Two consequences matter in practice.
- A plain
application.yamlnext to the jar overrides anapplication-prod.yamlthat is packaged inside the jar. Location outranks profile specificity. Many people expect the opposite. - Within the same location, a profile-specific file overrides the general one, and
.propertiesoverrides.yamlwhen both exist with the same name.
Multi-document YAML follows a simpler rule. Documents in one file are processed top to bottom, and a later document overrides an earlier one. A document guarded by spring.config.activate.on-profile applies only if that profile is active. Put profile documents after the defaults, or the defaults will overwrite them.
A worked example
Start with the file from the topic plan:
app:
mail:
host: localhost
port: 1025
sender: [email protected]
retry-attempts: 3
---
spring:
config:
activate:
on-profile: prod
app:
mail:
host: smtp.example.com
port: 587Now consider these launches and the value of app.mail.port in each:
| How the application starts | `app.mail.port` | Winner |
|---|---|---|
| `java -jar app.jar` | 1025 | First YAML document |
| `java -jar app.jar --spring.profiles.active=prod` | 587 | Profile document (later in the file) |
| `APP_MAIL_PORT=2600 java -jar app.jar --spring.profiles.active=prod` | 2600 | Environment variable beats config data |
| `APP_MAIL_PORT=2600 java -jar app.jar --app.mail.port=2525` | 2525 | Command line beats environment |
Each step adds a source that sits higher in the list, so the new value replaces the previous winner.
Finding the winning source in code
You do not have to guess. The Environment exposes its sources in priority order, so the first one that contains a key is the winner. This runner prints it at startup:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
@Component
class WinnerReport implements ApplicationRunner {
private final ConfigurableEnvironment environment;
WinnerReport(ConfigurableEnvironment environment) {
this.environment = environment;
}
@Override
public void run(ApplicationArguments args) {
String key = "app.mail.port";
for (PropertySource<?> source : environment.getPropertySources()) {
if (ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)) {
continue;
}
if (source.containsProperty(key)) {
System.out.println(key + " = " + source.getProperty(key)
+ " from " + source.getName());
break;
}
}
}
}The check for the attached source is needed. Spring Boot places a synthetic source named configurationProperties at the very top. It is an adapter that gives every other source a uniform view, and it contains every key. Without the continue, the loop would always report that adapter and never the real source.
Typical output is commandLineArgs for an override passed with --, systemEnvironment for an environment variable, and a name such as Config resource 'class path resource [application.yaml]' via location 'optional:classpath:/' (document #1) for a file. The document number tells you which YAML document won.
Merging rules and common errors
Overriding works per key, not per file. A higher source only replaces the keys it defines. If the command line sets app.mail.port, the host and sender still come from the lower sources. This is why a small override list works well in production.
Collections behave differently from scalars.
- Maps merge key by key across sources.
- Lists do not merge. If a higher source defines any element of
app.hosts[0], it replaces the whole list from the lower source. Do not expect an override to add an item.
Other common mistakes:
- Profile document placed first. The default document that follows overwrites it. Keep defaults first.
- Environment variable with the wrong spelling.
APP_MAIL_RETRY-ATTEMPTSwill not match. UseAPP_MAIL_RETRYATTEMPTSorAPP_MAIL_RETRY_ATTEMPTS. The next chapters cover relaxed binding. - Expecting
@PropertySourceto win. It is near the bottom of the list. A value there is overridden byapplication.yamland by every source above it. - Using
@PropertySourcewith YAML. It supports only.propertiesfiles by default. Usespring.config.importfor YAML. - Test values that seem ignored. Test sources have the highest priority, so a surprise usually means the test is not loading the context you think it is.
Summary of the working model
- The
Environmentis an ordered list of property sources, and the first source containing a key supplies its value. - Launch-time sources (command line, environment, system properties) beat files. Test sources beat everything.
- Among config files, location outranks profile: external files beat internal files, and within a location, profile-specific beats general.
- Override is per key. Maps merge. Lists are replaced.
Exercise
An application packages application.yaml with app.mail.port: 1025 and application-prod.yaml with app.mail.port: 587. In the directory where the jar runs, there is also an application.yaml containing app.mail.port: 3000. The application starts with --spring.profiles.active=prod and the environment variable APP_MAIL_PORT=2600. Which port does the application use, and what would it use if the environment variable were removed?
Show answer
It uses 2600, because environment variables are a higher-priority source than any config data file. Without the variable, it uses 3000. The external application.yaml is loaded after the packaged files, including the packaged application-prod.yaml, so it overrides the 587 value even though the profile is active.