Chapter 05

Configuration and profiles

One artifact, many environments. Get this chapter right and deployment becomes boring — which is exactly what you want deployment to be.

⏱ 18 min readLevel: beginner → intermediate

Where values come from

Spring merges many property sources into one Environment. When the same key appears twice, the higher-priority source wins. This order is worth memorising because "the property is being ignored" is nearly always a precedence question.

Ordered list of Spring Boot property sources from command line arguments down to defaults in code, plus notes on relaxed binding and profiles
Highest wins. Everything environment-specific should come from source 1 or 2.

Properties or YAML?

application.yml
spring:
  application:
    name: bookstore
  datasource:
    url: jdbc:postgresql://localhost:5432/bookstore
    username: bookstore_app
    password: ${DB_PASSWORD}          # from an environment variable
    hikari:
      maximum-pool-size: 20
      leak-detection-threshold: 20000
  jpa:
    open-in-view: false               # always set this — see chapter 8
    hibernate:
      ddl-auto: validate

server:
  port: 8080
  shutdown: graceful
  compression:
    enabled: true

bookstore:
  max-page-size: 100
  featured-categories: [fiction, science, history]
  cache:
    ttl: 10m
application.properties
spring.application.name=bookstore
spring.datasource.url=jdbc:postgresql://localhost:5432/bookstore
spring.datasource.username=bookstore_app
spring.datasource.password=${DB_PASSWORD}
spring.datasource.hikari.maximum-pool-size=20

spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=validate

server.port=8080
server.shutdown=graceful

bookstore.max-page-size=100
bookstore.featured-categories[0]=fiction
bookstore.featured-categories[1]=science
bookstore.cache.ttl=10m

Both are equivalent. YAML is easier to read for nested config; properties files avoid whitespace mistakes and are simpler to override from a shell. Pick one per project.

@Value vs @ConfigurationProperties

@Value — fine for one-offs
@Service
public class SearchService {

    private final int maxResults;

    public SearchService(@Value("${bookstore.max-page-size:25}") int maxResults) {
        this.maxResults = maxResults;
    }
}
@ConfigurationProperties — the real answer
package com.bitsnippets.bookstore.common;

@Validated
@ConfigurationProperties(prefix = "bookstore")
public record BookstoreProperties(

        @Min(1) @Max(500)
        @DefaultValue("100")
        int maxPageSize,

        @NotEmpty
        List<String> featuredCategories,

        @NestedConfigurationProperty
        CacheProperties cache) {

    public record CacheProperties(
            @DefaultValue("10m") Duration ttl,
            @DefaultValue("1000") int maximumSize) { }
}
enabling and using it
@SpringBootApplication
@ConfigurationPropertiesScan          // finds all @ConfigurationProperties types
public class BookstoreApplication { }

@Service
public class BookService {

    private final BookstoreProperties properties;

    public BookService(BookstoreProperties properties) {
        this.properties = properties;
    }

    public Page<Book> search(String query, int size) {
        int safeSize = Math.min(size, properties.maxPageSize());
        // ...
    }
}
@Value@ConfigurationProperties
Type safetyString-based, fails at runtimeReal types, fails at startup
ValidationNoneFull Bean Validation
Nesting / lists / mapsPainfulNative
Relaxed bindingNo — exact key onlyYes
IDE autocompletionNoYes, with the metadata processor
SpEL supportYesNo
Good forA single value, or SpELEverything else
Turn on IDE autocompletion for your own properties

Add the metadata processor and your custom keys autocomplete like Spring's own.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

Relaxed binding

@ConfigurationProperties matches keys loosely, which is what makes environment variables usable. All of these bind to maxPageSize:

all equivalent
bookstore.max-page-size=100      ← kebab-case, the canonical form
bookstore.maxPageSize=100        ← camelCase
bookstore.max_page_size=100      ← snake_case
BOOKSTORE_MAXPAGESIZE=100        ← environment variable
BOOKSTORE_MAX_PAGE_SIZE=100      ← environment variable
The rule for environment variables

Upper-case, and replace every non-alphanumeric character with an underscore. spring.datasource.password becomes SPRING_DATASOURCE_PASSWORD. This is how you configure a container without baking anything into the image. Note that @Value does not get relaxed binding — another reason to prefer @ConfigurationProperties.

Durations and data sizes

typed conversions come free
bookstore:
  cache:
    ttl: 10m              # → Duration.ofMinutes(10)
  http:
    timeout: 2s           # → Duration
  upload:
    max-size: 15MB        # → DataSize

Supported suffixes: ns, us, ms, s, m, h, d for durations and B, KB, MB, GB, TB for sizes. Use @DurationUnit if you want a bare number to mean something other than milliseconds.

Profiles

A profile is a named set of configuration and beans. application.yml always loads; application-{profile}.yml then overrides only the keys it declares.

application-dev.yml
spring:
  datasource:
    url: jdbc:h2:mem:bookstore
  jpa:
    hibernate:
      ddl-auto: create-drop
  h2:
    console:
      enabled: true

logging:
  level:
    com.bitsnippets.bookstore: DEBUG
    org.hibernate.SQL: DEBUG
application-prod.yml
spring:
  jpa:
    hibernate:
      ddl-auto: validate

logging:
  level:
    root: WARN
    com.bitsnippets.bookstore: INFO

management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus
activating them
# command line
java -jar bookstore.jar --spring.profiles.active=prod

# environment variable — the usual choice in containers
export SPRING_PROFILES_ACTIVE=prod,metrics

# in a test class
@ActiveProfiles("test")

Profile-scoped beans

swapping implementations per environment
public interface PaymentGateway {
    PaymentResult charge(Money amount, Card card);
}

@Component
@Profile("prod")
public class StripeGateway implements PaymentGateway { }

@Component
@Profile("!prod")                  // any profile except prod
public class FakeGateway implements PaymentGateway {

    @Override
    public PaymentResult charge(Money amount, Card card) {
        return PaymentResult.approved("fake-" + UUID.randomUUID());
    }
}

Expressions support !, & and |: @Profile("prod & !legacy") is valid.

Do not build a profile per customer

Profiles multiply combinatorially and each one is a code path nobody tests. Keep them to environment shapes (dev, test, prod) and express everything else as ordinary properties supplied by the environment. A profile that only changes property values should just be a set of environment variables.

Profile groups and multi-document files

application.yml
spring:
  profiles:
    group:
      # activating "production" activates all three
      production: prod,metrics,cloud

---
# a profile-specific section inside the same file
spring:
  config:
    activate:
      on-profile: dev
server:
  port: 8081

---
spring:
  config:
    activate:
      on-profile: prod
server:
  port: 8080

Secrets

Never commit a secret to application.yml

It ends up in the jar, in the container image, in the git history and in every developer's laptop backup. Rotating it then means a rebuild and a redeploy.

ApproachGood forWatch out for
Environment variablesAlmost everything; works everywhereVisible in /proc and crash dumps
Mounted files + spring.config.importKubernetes secretsFile permissions
Vault / AWS Secrets ManagerRotation and audit trailsExtra dependency and startup latency
Encrypted properties (Jasypt)Legacy setupsYou still must store the master key somewhere
importing extra config at startup
spring:
  config:
    import:
      - optional:file:/run/secrets/db.properties
      - optional:configtree:/run/secrets/       # k8s secret volume: one file per key
      - optional:file:./local.yml               # developer overrides, git-ignored

Fail fast on bad configuration

A misconfigured application should refuse to start, loudly, in the deployment pipeline — not fail at 3 a.m. on the first request that touches the bad value.

validated properties
@Validated
@ConfigurationProperties(prefix = "bookstore.inventory")
public record InventoryProperties(

        @NotBlank
        @Pattern(regexp = "https?://.+")
        String baseUrl,

        @NotNull
        @DurationMin(seconds = 1)
        @DurationMax(seconds = 30)
        Duration timeout,

        @Min(1) @Max(10)
        @DefaultValue("3")
        int retries) { }
the startup failure you want
***************************
APPLICATION FAILED TO START
***************************

Description:
Binding to target BookstoreProperties failed:

    Property: bookstore.inventory.timeout
    Value:    "45s"
    Reason:   must be less than or equal to 30 seconds

Action:
Update your application's configuration

Inspecting the resolved configuration

terminal
# every property and which source it came from
curl localhost:8080/actuator/env | jq

# one specific key, with all the sources that define it
curl localhost:8080/actuator/env/server.port | jq

# your bound @ConfigurationProperties objects
curl localhost:8080/actuator/configprops | jq
Never expose /actuator/env publicly

It prints your entire environment. Boot masks keys containing password, secret, key and token, but a key called db.credentials is not masked. Keep actuator on an internal port — chapter 12.

Checklist

  • @ConfigurationProperties for anything beyond a single value.
  • @Validated on every properties class, so bad config fails at startup.
  • Secrets from the environment, never from a file in the repository.
  • Profiles describe environments, not customers or features.
  • The same artifact ships to every environment; only variables differ.
  • spring.application.name is always set — logs and metrics depend on it.

A property is set in application-prod.yml and also as an environment variable. Which wins?

Environment variables are source 2; packaged profile files are source 5. The environment always wins over anything inside the jar — which is exactly what makes one build artifact deployable everywhere.