Sub topic 6
Overriding with environment variables and command-line arguments
This chapter assumes you know how to write application.yaml or application.properties, and that you have a basic idea of how Spring Boot ranks property sources. You should also know what a Spring bean is. Here you will learn how to change a single setting at launch time, without editing a file and without rebuilding the jar.
Why override at launch time
A jar is built once and then runs in many places: a laptop, a test server, production. The values inside the jar are defaults. The things that differ per environment (hostnames, ports, credentials) are better supplied from outside.
Spring Boot supports two main outside channels:
- Command-line arguments, which are visible in the launch command.
- Environment variables, which are set by the shell, a container runtime, or an orchestrator.
Both rank above the files packaged in the jar. If the same key appears in application.yaml and in one of these channels, the channel wins.
Command-line arguments
Any argument that starts with -- and has the form --key=value becomes a property. Spring Boot reads it through SimpleCommandLinePropertySource, and it is close to the top of the precedence list.
The examples in this chapter use the app.mail properties from the configuration file chapter.
# Activate a profile on the command line
java -jar app.jar --spring.profiles.active=prod
# Override a single property with a command-line argument
java -jar app.jar --app.mail.port=2525
# Override with environment variables (relaxed binding)
SPRING_PROFILES_ACTIVE=prod APP_MAIL_HOST=smtp.internal.example java -jar app.jarThe first command selects the prod profile. The second sets app.mail.port to 2525, whatever the file says. The third uses environment variables, which are covered next.
Details that cause trouble
- Write
--key=valuewith no spaces around=.--app.mail.port 2525is treated as an option namedapp.mail.portwith no value, followed by a separate non-option argument2525. - Arguments that do not start with
--are not properties. Spring Boot passes them to your application as non-option arguments. - If you run through Maven or Gradle, the build tool must forward the argument. With Maven, use
mvn spring-boot:run -Dspring-boot.run.arguments="--app.mail.port=2525". With Gradle, use./gradlew bootRun --args="--app.mail.port=2525". - Command-line properties can be turned off with
SpringApplication.setAddCommandLineProperties(false). This is rarely needed, but it explains why they sometimes seem to be ignored in a custom launcher.
Environment variables
Operating systems restrict the names of environment variables. In most shells they may contain letters, digits, and underscores, but not dots or hyphens. So app.mail.port cannot be an environment variable name. Spring Boot solves this with a naming convention, which is part of relaxed binding.
To convert a property name to an environment variable name:
- Replace each dot with an underscore.
- Remove any hyphens.
- Convert the result to uppercase.
| Property name | Environment variable |
|---|---|
| `app.mail.host` | `APP_MAIL_HOST` |
| `app.mail.retry-attempts` | `APP_MAIL_RETRYATTEMPTS` |
| `spring.profiles.active` | `SPRING_PROFILES_ACTIVE` |
| `server.port` | `SERVER_PORT` |
Note the hyphen rule. retry-attempts becomes RETRYATTEMPTS, not RETRY_ATTEMPTS. Many people guess the second form, and it does not bind.
export APP_MAIL_RETRYATTEMPTS=5
java -jar app.jarLists and indexes
Lists need an index in the name, surrounded by underscores. For a property app.mail.recipients[0], use:
export [email protected]Because this is awkward, a comma-separated value is often easier for a simple list of strings:
export [email protected],[email protected]Both forms work when the target property is a List<String>.
Where the convention is applied
The conversion matters in two situations. Binding to a @ConfigurationProperties class, such as MailProperties, understands the uppercase form fully. A lookup with @Value("${app.mail.host}") or environment.getProperty("app.mail.host") also finds APP_MAIL_HOST, because Spring Boot maps the system environment source so that these lookups work for simple names.
For this reason, write the canonical lowercase form (app.mail.host) in your code and files. Use the uppercase form only when you set variables outside the application.
Which one wins
When the same property is defined in several places, the higher-ranked source wins. The relevant part of the order, from highest to lowest, is:
- Command-line arguments.
- Java system properties (
-Dapp.mail.port=2525). - OS environment variables.
- Config files outside the jar (profile-specific first).
- Config files inside the jar (profile-specific first).
- Defaults set in code.
The complete list has more entries, such as test properties and JSON in SPRING_APPLICATION_JSON, but this subset covers daily work.
The diagram shows what happens for app.mail.port when the value is set in several places.
For example, suppose the jar contains app.mail.port: 1025, the environment has APP_MAIL_PORT=587, and you launch with --app.mail.port=2525. The application sees 2525. Remove the argument and it sees 587. Remove the variable and it sees 1025.
Overriding a profile's value
Profile-specific values in files, such as the prod document in the example application.yaml, are still files. An environment variable or command-line argument beats them. So APP_MAIL_HOST=smtp.internal.example replaces smtp.example.com even when prod is active. This is the usual way to adapt a single deployment without a new profile.
Passing values through containers and orchestrators
Containers are the most common place where environment variables are used. In Docker you can write:
docker run -e SPRING_PROFILES_ACTIVE=prod -e APP_MAIL_HOST=smtp.internal.example myapp:1.0In Kubernetes, the same variables are set in the env section of a container spec, and sensitive ones come from a Secret. The application does not need to know where they came from.
Interaction with binding and validation
Overrides pass through the same binding as file values. If MailProperties has @Min(1) @Max(65535) on the port, then --app.mail.port=70000 stops the application at startup with a binding error. A non-numeric value such as --app.mail.port=abc fails with a conversion error. This is a useful property of the mechanism: a bad override is caught at launch, not when the first email is sent.
Common errors
- Wrong hyphen handling.
APP_MAIL_RETRY_ATTEMPTSis a different variable fromAPP_MAIL_RETRYATTEMPTS. Only the second binds toapp.mail.retry-attempts. - Variable set in the wrong shell.
exportin one terminal does not affect an application launched from another terminal or from an IDE run configuration. - Spaces in values. Quote values that contain spaces or special characters, for example
--app.mail.sender="no [email protected]". The shell removes the quotes before Spring Boot sees them. - Expecting a rename. Overriding replaces a value. It does not add a new key unless your code reads that key.
- Hidden overrides. An old variable left in a CI job or container definition can silently beat the file you just edited. When a value looks wrong, check the highest-ranked sources first.
Checking your understanding
Exercise
A jar contains app.mail.retry-attempts: 3 in application.yaml. The deployment sets the environment variable APP_MAIL_RETRY_ATTEMPTS=9 and starts the app with --app.mail.retry-attempts=5. What value does MailProperties.retryAttempts() have, and what would it be if the command-line argument were removed?
Show answer
It is 5, because command-line arguments rank above environment variables. Without the argument it is 3, not 9. APP_MAIL_RETRY_ATTEMPTS does not match the property, because hyphens are removed and not replaced with underscores. The correct variable name is APP_MAIL_RETRYATTEMPTS.
Exercise
Write the command that starts app.jar with the prod profile and the mail port set to 2525, using only environment variables.
Show answer
SPRINGPROFILESACTIVE=prod APPMAILPORT=2525 java -jar app.jar
Exercise
You launch with --app.mail.port 2525 (a space instead of =). The port does not change. Why?
Show answer
Spring Boot reads --app.mail.port as an option with no value, and 2525 as a separate non-option argument. The property gets an empty value, or the file value is overridden by an empty one, so the intended port is never set. Use --app.mail.port=2525.