Sub topic 3
Keeping configuration outside the artifact
This chapter assumes you can build a Spring Boot executable JAR and run it with java -jar. It also assumes you know what an environment variable is and have used application.properties before. Secrets get their own chapter, so here we focus on the mechanism that carries all configuration, including secrets, into a running application.
Why configuration stays outside the JAR
You build the artifact once and run it in several places: your laptop, a test server, production. The database URL, the port, and the log level differ between those places. If you bake these values into the JAR, you must rebuild for each environment. The JAR you tested is then not the JAR you ship.
The rule is: build once, configure at run time. The artifact holds defaults that are safe everywhere. The environment supplies everything that varies.
How Spring Boot finds property values
Spring Boot reads configuration from many sources and merges them into one Environment. When two sources set the same property, the source with higher precedence wins. The ones you will use for deployment, from highest to lowest, are:
- Command-line arguments, such as
--server.port=9090. - Java system properties, such as
-Dserver.port=9090. - OS environment variables, such as
SERVER_PORT=9090. - Profile-specific files outside the JAR, such as
./config/application-prod.properties. - Application files outside the JAR, such as
./config/application.properties. - Profile-specific files inside the JAR, such as
application-prod.properties. - Application files inside the JAR, such as
application.properties. - Defaults in code, such as
@Value("${x:default}")orSpringApplication.setDefaultProperties.
The full list in the Spring Boot reference has more entries, but this ordering covers the deployment cases. The key point is that anything outside the JAR beats anything inside it. That is what lets a single artifact be reconfigured.
Environment variables and relaxed binding
Environment variables cannot contain dots or hyphens in many shells. Spring Boot handles this with relaxed binding. It maps a property name to an environment variable name by these steps:
- Replace dots with underscores.
- Remove hyphens.
- Convert to uppercase.
| Property | Environment variable |
|---|---|
| `server.port` | `SERVER_PORT` |
| `spring.datasource.url` | `SPRING_DATASOURCE_URL` |
| `app.max-retries` | `APP_MAXRETRIES` |
| `spring.profiles.active` | `SPRING_PROFILES_ACTIVE` |
The hyphen rule trips people up. app.max-retries becomes APP_MAXRETRIES, not APP_MAX_RETRIES. If you write the second form, the value is silently ignored.
Placeholders in the packaged file
You do not have to name every override by its relaxed form. A common pattern is to put a placeholder in the packaged file and let the environment fill it in:
# application.properties
server.port=8080
server.shutdown=graceful
spring.datasource.url=${DB_URL}
spring.datasource.password=${DB_PASSWORD}
app.greeting=${APP_GREETING:Hello}${DB_URL} has no default. If the variable is missing, the application fails at startup with an unresolved placeholder error. This is useful: a missing database URL stops the deployment instead of letting the app run misconfigured. ${APP_GREETING:Hello} supplies a default after the colon, so it never fails.
Here is a bean that reads these values with type-safe binding:
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app")
public record AppProperties(String greeting, int maxRetries) {
}Register it by adding @ConfigurationPropertiesScan to your application class, or @EnableConfigurationProperties(AppProperties.class) to a configuration class. Then app.max-retries, app.maxRetries, and APP_MAXRETRIES all bind to maxRetries. Because int has no default here, add a default in the properties file, such as app.max-retries=3, or the record gets 0.
Profiles
A profile is a named set of configuration for one kind of environment. Activate one or more with spring.profiles.active. Spring then loads application-{profile}.properties on top of the base file.
# application-prod.properties
logging.level.root=WARN
management.endpoints.web.exposure.include=health,infoYou can activate a profile in any source:
# Command-line argument
java -jar target/myapp-1.0.0.jar --spring.profiles.active=prod
# Environment variable
SPRING_PROFILES_ACTIVE=prod java -jar target/myapp-1.0.0.jar
# System property (must come before -jar)
java -Dspring.profiles.active=prod -jar target/myapp-1.0.0.jarKeep profiles for behavior that differs by kind of environment, such as log levels or which beans exist. Do not use them to store per-environment hostnames or credentials in the JAR. A application-prod.properties that contains the production database password defeats the purpose of this chapter.
Profile-specific files override the base file, but they do not replace it. Properties not set in application-prod.properties still come from application.properties.
External configuration files
Spring Boot also looks for files next to the JAR. By default it checks, in this order of increasing precedence:
- The classpath root, inside the JAR.
- A
/configpackage on the classpath, inside the JAR. - The current working directory.
- A
config/subdirectory of the working directory. - Immediate child directories of
config/.
Later locations win. So if you run the JAR from /opt/myapp, a file at /opt/myapp/config/application.properties overrides the packaged one.
You can point at other places explicitly:
java -jar app.jar --spring.config.additional-location=file:/etc/myapp/
java -jar app.jar --spring.config.location=file:/etc/myapp/application.propertiesThe two options behave differently. additional-location adds to the default locations and takes precedence over them. location replaces the defaults entirely, so the packaged application.properties is no longer loaded. That is a frequent source of "my defaults disappeared" bugs.
Another option is spring.config.import, which you set in the packaged file to pull in an optional external file:
spring.config.import=optional:file:/etc/myapp/local.propertiesThe optional: prefix means startup continues if the file does not exist. Without it, a missing file stops the application.
Command-line arguments
Arguments of the form --name=value after the JAR name become properties with the highest precedence among the sources above:
java -jar target/myapp-1.0.0.jar --server.port=9090 --app.greeting=HiOrder matters on the command line. JVM options such as -Xmx512m and -D... go before -jar. Application arguments go after the JAR file name. An option placed on the wrong side is either ignored by your app or rejected by the JVM.
Command-line arguments are visible to anyone who can list processes on the machine, for example with ps. Use them for non-sensitive settings. For passwords, prefer a source that is not exposed that way, which the next chapter on secrets covers.
Working through an example
Suppose the packaged application.properties contains server.port=8080 and app.greeting=${APP_GREETING:Hello}. You start the app like this:
APP_GREETING=Bonjour SERVER_PORT=8081 \
java -jar target/myapp-1.0.0.jar --server.port=9090The resulting values are:
| Property | Value | Winning source |
|---|---|---|
| `server.port` | `9090` | Command-line argument |
| `app.greeting` | `Bonjour` | Environment variable via placeholder |
SERVER_PORT=8081 loses to the command-line argument, and the packaged 8080 loses to both.
Seeing what the app actually used
When a value is not what you expect, ask the running application. With Actuator on the classpath, expose the env endpoint temporarily in a non-production setting:
management.endpoints.web.exposure.include=health,info,envThen request /actuator/env/server.port. The response lists each source that defines the property and which one won. Spring Boot masks values for keys that look sensitive, but you should still keep env unexposed in production because it reveals your configuration layout.
You can also start the application with --debug to print the condition evaluation report, or log at DEBUG for org.springframework.boot.context.config to see which files were loaded.
Common errors
- Unresolved placeholder at startup. A
${NAME}with no default and no matching variable. Set the variable or add a default. - Variable ignored. The name does not follow relaxed binding, often an underscore where a hyphen was removed. Check the table above.
- Profile does nothing. The file name does not match, for example
application-production.propertieswith--spring.profiles.active=prod. - Defaults vanish. You used
spring.config.locationwhere you meantspring.config.additional-location. - JVM flag treated as an app argument.
-Dspring.profiles.active=prodplaced after the JAR name is passed to yourmainmethod and has no effect as a system property. - Changes not picked up. Configuration is read at startup. Changing an environment variable or file requires a restart, unless you add a mechanism such as Spring Cloud for refresh.
Summary of the decisions
| Need | Use |
|---|---|
| One-off override while testing | Command-line argument |
| Per-environment values in containers or services | Environment variables |
| Many related settings managed as a file | External file in `config/` or `spring.config.additional-location` |
| Behavior that differs by environment type | A profile |
| A value that must exist or startup fails | Placeholder with no default |
Exercise
A JAR contains server.port=8080 in application.properties. You run SERVER_PORT=8081 java -Dserver.port=8082 -jar app.jar --server.port=8083. Which port does the app use, and what happens to the other three values?
Show answer
The app listens on 8083. Command-line arguments have the highest precedence, then system properties (8082), then environment variables (8081), then the packaged file (8080). The three lower values are still present in their sources but are overridden for the server.port property.
Exercise
Your packaged file has app.max-retries=3. You set APP_MAX_RETRIES=10 on the server, but the app still uses 3. Why, and what is the correct variable name?
Show answer
Relaxed binding removes hyphens when mapping to an environment variable, so app.max-retries maps to APP_MAXRETRIES. APP_MAX_RETRIES does not match any property, so Spring ignores it. Set APP_MAXRETRIES=10.
Exercise
After adding --spring.config.location=file:/etc/myapp/application.properties, the app fails with an unresolved placeholder for a property that has a default in the packaged application.properties. What changed, and how do you fix it?
Show answer
spring.config.location replaces the default search locations, so the packaged file is no longer loaded and its defaults are gone. Use spring.config.additional-location instead, which adds the external file on top of the defaults.