Lesson 3 of 12 · 9 min · Spring core
Profiles and externalized configuration
What you will learn
- Configure an application with
application.propertiesor YAML - Know the order in which Spring Boot reads configuration
- Bind properties to a typed class with
@ConfigurationProperties - Use profiles for development, test and production
- Keep secrets out of the code and the repository
In simple words
The same program must behave differently on your laptop, in testing and in production: different database, different passwords, different log levels. You do not rebuild the program for each place. Instead, the program reads its settings from outside, such as a file or environment variables, and you change the settings, not the code. A profile is a named set of settings, like "dev" or "prod", that you switch on when you start the app.
Words to know
- Property: a named setting, such as
server.port=8081. - Externalized configuration: keeping settings outside the compiled code.
- Profile: a named group of beans and settings activated for a particular environment.
- Environment variable: a setting provided by the operating system or container.
application.properties and YAML
Boot reads src/main/resources/application.properties (or application.yml) automatically:
server.port=8081
spring.application.name=shop
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.jpa.hibernate.ddl-auto=validate
logging.level.com.shop=DEBUG
The same in YAML (indentation matters; use spaces):
server:
port: 8081
spring:
application:
name: shop
datasource:
url: jdbc:postgresql://localhost:5432/shop
username: shop
logging:
level:
com.shop: DEBUG
The official reference lists every common property (the "Application Properties" appendix). Your IDE autocompletes them. Properties can reference others: app.url=http://localhost:${server.port}.
Where values come from (precedence)
Boot merges many sources; later ones override earlier ones. A simplified order, from lowest to highest priority:
- Defaults in code and
@PropertySource. application.properties/application.ymlpackaged in the JAR.application.propertiesoutside the JAR (in the working directory orconfig/).- Profile-specific files (
application-prod.properties). - OS environment variables (
SERVER_PORT=9090). - Command-line arguments (
--server.port=9090).
So you can ship safe defaults inside the JAR and override anything per environment without changing the code. Environment variables use relaxed binding: SPRING_DATASOURCE_URL maps to spring.datasource.url, and APP_PAYMENT_TIMEOUT to app.payment.timeout. This is how containers and cloud platforms (Docker, Kubernetes) configure apps. A configuration file can also import others: spring.config.import=optional:file:./secrets.properties.
Typed configuration with @ConfigurationProperties
Reading single values with @Value is easy but untyped and scattered:
@Value("${app.payment.timeout:5s}") // default 5s if missing
private Duration timeout;
For groups of settings, bind to a class. A record works well (immutable):
@ConfigurationProperties(prefix = "app.payment")
public record PaymentProperties(String baseUrl, Duration timeout, int retries) {}
app.payment.base-url=https://pay.example.com
app.payment.timeout=3s
app.payment.retries=2
Enable scanning for it with @ConfigurationPropertiesScan on the main class (or @EnableConfigurationProperties(PaymentProperties.class)), and inject PaymentProperties like any bean. Benefits: type conversion (Duration, DataSize, lists, maps), validation with @Validated and Bean Validation annotations (the app fails at startup on a bad value), relaxed names (base-url in files binds to baseUrl), and IDE metadata when you add spring-boot-configuration-processor. Prefer @ConfigurationProperties over many @Value annotations.
Profiles
A profile switches on environment-specific settings and beans.
Profile-specific files: application-dev.properties, application-prod.properties. Values in the active profile's file override application.properties.
# application.properties (defaults)
spring.jpa.show-sql=false
# application-dev.properties
spring.jpa.show-sql=true
spring.datasource.url=jdbc:h2:mem:shop
logging.level.com.shop=DEBUG
Activate profiles:
java -jar app.jar --spring.profiles.active=prod
SPRING_PROFILES_ACTIVE=prod java -jar app.jar
or in properties (spring.profiles.active=dev, handy for local defaults only; do not hard-code prod). If none is active, the default profile applies. In tests, @ActiveProfiles("test") selects the test profile. You can activate several (dev,local), and profile groups (spring.profiles.group.prod=proddb,prodmq) bundle them.
Profile-specific beans:
@Configuration
@Profile("dev")
class DevConfig {
@Bean
EmailSender emailSender() { return new LoggingEmailSender(); } // prints instead of sending
}
@Service
@Profile("prod")
class SmtpEmailSender implements EmailSender { ... }
In YAML, one file can hold several profile sections separated by --- with spring.config.activate.on-profile: prod.
Use profiles for environment differences (databases, external endpoints, logging, fake versus real integrations), not for feature flags per customer or to hide logic differences that tests cannot cover. Keep the number of profiles small, because each one is another configuration to test.
Secrets
Never commit passwords, API keys or tokens to Git, even in a private repository. Instead:
- Provide them through environment variables or the platform's secret store (Kubernetes Secrets, Docker secrets, cloud secret managers such as AWS Secrets Manager, HashiCorp Vault).
- Use a local file that is in
.gitignorefor development (secrets.propertiesimported withoptional:). - Reference them in properties by placeholder:
spring.datasource.password=${DB_PASSWORD}. - Be careful not to log them or expose them through Actuator (
management.endpoint.env, and note Boot sanitises known sensitive keys by default but not everything). - If a secret was committed by mistake, rotate it (change it); removing the commit is not enough.
Provide a application-example.properties or .env.example without real values so teammates know what is needed.
Useful settings to know
| Property | Meaning |
|---|---|
server.port |
HTTP port (use 0 for a random port in tests) |
spring.application.name |
name for logs and metrics |
spring.datasource.* |
database connection and pool |
spring.jpa.hibernate.ddl-auto |
none/validate in production; create-drop only for throwaway tests |
spring.jpa.open-in-view |
set to false (see the JPA lessons) |
logging.level.<package> |
log levels |
spring.jackson.* |
JSON options (Boot 4 uses Jackson 3, some keys moved) |
management.endpoints.web.exposure.include |
which Actuator endpoints are exposed |
Common mistakes
- Committing secrets to the repository.
- Hard-coding values instead of properties.
- Using
ddl-auto=updatein production (use migrations with Flyway or Liquibase). - Activating
prodin a file in Git so developers run against production. - Scattering
@Valuestrings with no validation or defaults. - Too many profiles, with environments that cannot be reproduced.
- Misspelled property names that are silently ignored (check with the IDE and
@ConfigurationPropertiesvalidation).
Try it yourself
- Add
application-dev.propertiesandapplication-prod.propertieswith different log levels and run with each profile. - Override
server.portusing an environment variable and then a command-line argument; note which wins. - Create
PaymentPropertiesas a record with@ConfigurationPropertiesand validate thatretriesis at least 1. - Create a
@Profile("dev")bean that logs emails and a@Profile("prod")one that would send them. - Move the database password out of
application.propertiesinto an environment variable.
Check yourself
Which has higher priority, a value in application.properties or an environment variable?
The environment variable; externalised sources such as environment variables and command-line arguments override the files packaged in the JAR.
Why prefer @ConfigurationProperties to @Value?
It binds a group of related settings to a typed, validated, documented class and supports relaxed names, instead of scattered untyped strings.
How do you activate a profile?
With spring.profiles.active, as a property, environment variable SPRING_PROFILES_ACTIVE or command-line argument --spring.profiles.active=prod.
How should secrets be provided to a Spring Boot application?
Through environment variables or a secret store, referenced by placeholders, never committed to source control.
Interview questions
How do you manage different configurations for dev, test and production?
Keep defaults in application.properties, add profile-specific files or sections, activate the profile through an environment variable or command-line argument, and supply secrets from the environment or a secret manager.
What is relaxed binding?
Boot's flexible matching of property names, so app.payment-timeout, app.paymentTimeout and the environment variable APP_PAYMENT_TIMEOUT all map to the same property.
What does @Profile do?
It registers a bean or configuration class only when the specified profile is active.
Summary
- Configure through
application.propertiesor YAML; external sources override packaged ones. - Bind groups of properties to records with
@ConfigurationPropertiesand validate them. - Use profiles for environment differences; activate with an environment variable or argument.
- Keep secrets out of Git; supply them from the environment or a secret store.
Going deeper
- Spring Boot: Externalized configuration: sources, precedence and binding.
- Spring Boot: Profiles: activating and grouping profiles.
- Common application properties: every standard property.
- Spring Boot: Configuration metadata: IDE support for your own properties.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.