Configuration and profiles
One artifact, many environments. Get this chapter right and deployment becomes boring — which is exactly what you want deployment to be.
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.
Properties or YAML?
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
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
@Service
public class SearchService {
private final int maxResults;
public SearchService(@Value("${bookstore.max-page-size:25}") int maxResults) {
this.maxResults = maxResults;
}
}
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) { }
}
@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 safety | String-based, fails at runtime | Real types, fails at startup |
| Validation | None | Full Bean Validation |
| Nesting / lists / maps | Painful | Native |
| Relaxed binding | No — exact key only | Yes |
| IDE autocompletion | No | Yes, with the metadata processor |
| SpEL support | Yes | No |
| Good for | A single value, or SpEL | Everything else |
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:
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
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
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.
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
spring:
jpa:
hibernate:
ddl-auto: validate
logging:
level:
root: WARN
com.bitsnippets.bookstore: INFO
management:
endpoints:
web:
exposure:
include: health,info,prometheus
# 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
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.
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
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
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.
| Approach | Good for | Watch out for |
|---|---|---|
| Environment variables | Almost everything; works everywhere | Visible in /proc and crash dumps |
Mounted files + spring.config.import | Kubernetes secrets | File permissions |
| Vault / AWS Secrets Manager | Rotation and audit trails | Extra dependency and startup latency |
| Encrypted properties (Jasypt) | Legacy setups | You still must store the master key somewhere |
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
@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) { }
***************************
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
# 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
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
@ConfigurationPropertiesfor anything beyond a single value.@Validatedon 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.nameis 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.