TExcelTAD
Home › Spring Boot › Configuration for Environments

Configuration for Environments

The Twelve-Factor App rule is simple: build once, configure per environment. The JAR or image that passed your tests is the very same artifact that runs in staging and production — only its configuration differs. This lesson pulls together everything Spring Boot offers for that: property source order, environment variables, config imports, secrets and safe defaults.

What varies, and where it should live

Setting Example Where
behaviour defaults page size, timeouts application.yml in the JAR
environment differences log format, feature toggles profile files or env vars
infrastructure addresses DB URL, broker host env vars / platform config
secrets DB password, API keys secret store, injected as env vars or files — never in Git

A production-ready base configuration

yaml
spring:
  application:
    name: tasks
  datasource:
    url: ${DB_URL:jdbc:postgresql://localhost:5432/tasks}
    username: ${DB_USER:tasks}
    password: ${DB_PASSWORD}            # no default: must be provided
  jpa:
    open-in-view: false
    hibernate:
      ddl-auto: validate
  threads:
    virtual:
      enabled: true
server:
  shutdown: graceful
  forward-headers-strategy: framework  # behind a reverse proxy / load balancer
management:
  server:
    port: 8081
  endpoints:
    web:
      exposure:
        include: health,info,prometheus

${DB_PASSWORD} without a default makes startup fail fast if the variable is missing — far better than connecting with an empty password.

The override order (highest first)

# Source
1 command-line arguments --key=value
2 SPRING_APPLICATION_JSON
3 Java system properties -Dkey=value
4 OS environment variables
5 profile-specific files outside the JAR (./config/application-prod.yml)
6 profile-specific files inside the JAR
7 application.yml outside the JAR (./config/, current directory)
8 application.yml inside the JAR
9 @PropertySource and defaults

The following program resolves a few keys through a stack of sources in this order, and reports which source won — the same question /actuator/env answers in a running app:

java · try it yourself
import java.util.*;

record Source(String name, Map<String, String> values) {}

class Main {
    static String resolve(List<Source> sources, String key) {
        for (Source s : sources) {
            String v = s.values().get(key);
            if (v != null) return String.format("%-32s = %-38s (from %s)", key, v, s.name());
        }
        return String.format("%-32s   MISSING -> startup fails", key);
    }

    public static void main(String[] args) {
        List<Source> sources = List.of(          // highest priority first
            new Source("commandLineArgs", Map.of("server.port", "9000")),
            new Source("systemEnvironment", Map.of(
                "spring.datasource.url", "jdbc:postgresql://db.prod:5432/tasks",
                "spring.datasource.password", "********")),
            new Source("application-prod.yml", Map.of(
                "logging.structured.format.console", "ecs", "server.port", "8080")),
            new Source("application.yml", Map.of(
                "server.port", "8080", "tasks.page-size", "20",
                "spring.datasource.url", "jdbc:postgresql://localhost:5432/tasks")));

        for (String key : List.of("server.port", "spring.datasource.url", "spring.datasource.password",
                "logging.structured.format.console", "tasks.page-size", "tasks.mail.api-key")) {
            System.out.println(resolve(sources, key));
        }
    }
}
server.port                      = 9000                                   (from commandLineArgs)
spring.datasource.url            = jdbc:postgresql://db.prod:5432/tasks   (from systemEnvironment)
spring.datasource.password       = ********                               (from systemEnvironment)
logging.structured.format.console = ecs                                    (from application-prod.yml)
tasks.page-size                  = 20                                     (from application.yml)
tasks.mail.api-key                 MISSING -> startup fails

(The real environment maps SPRING_DATASOURCE_URL to spring.datasource.url via relaxed binding; the model stores the already-mapped names.)

Inspecting the real environment

bash · try it yourself
curl -s localhost:8081/actuator/env/server.port | jq '.property'
{
  "source": "commandLineArgs",
  "value": "9000"
}

In Spring Boot 3, the env and configprops endpoints mask all values as ****** unless you set management.endpoint.env.show-values (when-authorized is a sensible choice; the output above assumes it). Even then, keys that look sensitive (password, secret, key, token…) stay masked.

Importing extra configuration

spring.config.import loads additional sources. The optional: prefix means "fine if it doesn't exist":

yaml
spring:
  config:
    import:
      - optional:file:./.env[.properties]     # local developer overrides, git-ignored
      - optional:configtree:/run/secrets/     # Docker/Kubernetes secret files

With a config tree, every file in the directory becomes a property: the file /run/secrets/spring.datasource.password containing s3cr3t sets spring.datasource.password=s3cr3t. This is how Kubernetes secrets mounted as volumes are typically consumed.

Environment in Docker Compose

yaml
services:
  app:
    image: example/tasks:1.4.0
    ports: ["8080:8080"]
    environment:
      SPRING_PROFILES_ACTIVE: prod
      DB_URL: jdbc:postgresql://db:5432/tasks
      DB_USER: tasks
      DB_PASSWORD: ${DB_PASSWORD}        # taken from the shell or a git-ignored .env file
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17
    environment:
      POSTGRES_DB: tasks
      POSTGRES_USER: tasks
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "tasks"]
      interval: 5s

Docker Compose substitutes ${DB_PASSWORD} from your shell or from a .env file next to compose.yaml (keep that file out of Git). In Kubernetes the same variable would come from a Secret.

bash · try it yourself
docker compose up -d && docker compose ps --format "table {{.Service}}\t{{.Status}}"
[+] Running 3/3
 ✔ Network tasks_default  Created
 ✔ Container tasks-db-1   Healthy
 ✔ Container tasks-app-1  Started
SERVICE   STATUS
app       Up 2 seconds
db        Up 8 seconds (healthy)

Tip: For local development, Spring Boot's spring-boot-docker-compose module can start the services in your compose.yaml automatically when you run the app, and wire the connection details without any properties.

Checklist

  • Defaults in application.yml make the app runnable locally with minimal setup.
  • Everything that differs per environment can be overridden by an environment variable.
  • Secrets have no defaults and never appear in Git, logs or /actuator/env.
  • ddl-auto=validate plus Flyway in every environment except throwaway tests.
  • The same image is promoted from test to production — never rebuilt.

Test yourself

A key is set in application.yml inside the JAR and as an OS environment variable. Which wins?

  1. application.yml
  2. The environment variable
  3. Whichever was set last
  4. Startup fails

What does optional: mean in spring.config.import=optional:file:./.env[.properties]?

  1. The file is loaded only in tests
  2. Missing files are ignored instead of failing startup
  3. Values from it are optional
  4. It is loaded lazily

Why give spring.datasource.password no default value?

  1. Defaults are not allowed for passwords
  2. So startup fails fast when the secret is not provided
  3. To speed up startup
  4. Spring generates one automatically