Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 119 ยท Spring Boot

Configuration, Properties and Profiles

Configure Spring Boot apps - application.properties and YAML, @Value, type-safe @ConfigurationProperties records, profiles, environment variables and override order.

The same application runs on your laptop, in the test pipeline and in production, but with a different database, different log levels, different API keys. Hard-coding those values means rebuilding for every environment and committing secrets to Git. Spring Boot solves this with externalized configuration: the code asks for a setting by name, and Boot finds the value in one of many places (property files, YAML, environment variables, command-line arguments), with a precise rule for which source wins.

In this lesson you will learn the file formats, the two ways to read settings in code (@Value and the type-safe @ConfigurationProperties), profiles for environment-specific settings, and the override order that decides the final value. The runnable examples rebuild Boot's Environment in plain Java, so you can watch values being looked up, overridden, converted and validated. You should know Spring Boot Introduction first.

application.properties and application.yml

Boot reads src/main/resources/application.properties automatically. Keys are dot-separated, lowercase and kebab-case:

PROPERTIES
spring.application.name=shop
server.port=8080

spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.datasource.password=${DB_PASSWORD}

logging.level.org.springframework.web=DEBUG

shop.mail.host=smtp.example.com
shop.mail.timeout=10s
[email protected],[email protected]

The same settings in YAML (application.yml) are grouped by indentation, which helps with long prefixes:

YAML
spring:
  application:
    name: shop
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
    password: ${DB_PASSWORD}

shop:
  mail:
    host: smtp.example.com
    timeout: 10s
    recipients:
      - [email protected]
      - [email protected]

Both formats work equally well; pick one per project. YAML is whitespace-sensitive (use spaces, never tabs) and has surprises such as no and off being read as booleans in some YAML versions, so quote values when in doubt. If both files exist in the same place, .properties wins.

Boot defines hundreds of spring.*, server.*, logging.* and management.* properties. Your IDE completes them from the metadata shipped in Boot's JARs; the "Common Application Properties" appendix in the Boot reference lists them all. Use your own prefix (shop.* here) for your application's settings.

Placeholders

${...} refers to another property or an environment variable, with an optional default after a colon:

PROPERTIES
app.base-url=https://${APP_HOST:localhost}:${server.port}
app.instance-id=${random.uuid}

If DB_PASSWORD has no value and no default, startup fails with "Could not resolve placeholder", which is what you want for a required secret: fail fast instead of running with a wrong value.

Where values come from, and who wins

Boot collects property sources into the Environment and searches them in order. The first source that has the key wins. The most useful part of the order, from highest to lowest priority:

Priority Source Example
1 Command-line arguments java -jar app.jar --server.port=9090
2 SPRING_APPLICATION_JSON SPRING_APPLICATION_JSON='{"server":{"port":9090}}'
3 Java system properties java -Dserver.port=9090 -jar app.jar
4 OS environment variables SERVER_PORT=9090
5 Profile-specific files outside the JAR ./config/application-prod.properties
6 Application files outside the JAR ./application.properties, ./config/application.properties
7 Profile-specific files inside the JAR application-prod.properties in resources
8 Application files inside the JAR application.properties in resources
9 @PropertySource and default properties Rarely used

(Tests add even higher sources, such as @TestPropertySource and the properties attribute of @SpringBootTest.) The design is deliberate: the JAR carries sensible defaults, and every environment overrides only what differs, without rebuilding.

Environment variables can't contain dots or dashes, so Boot maps them with relaxed binding: uppercase, dots become underscores, dashes are removed. spring.datasource.url becomes SPRING_DATASOURCE_URL, and shop.mail.max-retries becomes SHOP_MAIL_MAXRETRIES. List elements use the index as a segment ([email protected]), but a comma-separated value usually works too. This is how containers and cloud platforms usually configure Boot apps.

The following program builds a small Environment with four sources, in Boot's order, and resolves several keys. For each value it prints which source supplied it, like the /actuator/env endpoint does. It also resolves placeholders with defaults.

Java Property sources, override order and relaxed names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output line by line: the port comes from the command line even though two files define it; the mail host from the external file; max-retries and the database URL from environment variables written in their relaxed form; the base URL combines a default (localhost, because APP_HOST isn't set) with the overridden port. The last key exists nowhere, which is a startup error in Boot.

Reading values with @Value

The quickest way to use a property is @Value on a field or, better, a constructor parameter:

Java
@Service
public class InvoiceService {
    private final String currency;
    private final int maxRetries;

    public InvoiceService(@Value("${shop.currency:EUR}") String currency,
                          @Value("${shop.mail.max-retries}") int maxRetries) {
        this.currency = currency;
        this.maxRetries = maxRetries;
    }
}

@Value is fine for one or two settings. It has limits: each key is a string scattered through the code, typos are found only at runtime, there is no validation, and nothing groups related settings. Write the key in canonical kebab-case (max-retries), so relaxed binding can still find environment variables like SHOP_MAIL_MAXRETRIES.

Type-safe configuration with @ConfigurationProperties

For anything bigger, bind a whole prefix to a class. Records are a perfect fit:

Java
@ConfigurationProperties(prefix = "shop.mail")
@Validated
public record MailProperties(
        @NotBlank String host,
        @DefaultValue("587") @Min(1) @Max(65535) int port,
        @DefaultValue("10s") Duration timeout,
        @DefaultValue("3") int maxRetries,
        List<@Email String> recipients,
        @DefaultValue("true") boolean enabled) {
}

@SpringBootApplication
@ConfigurationPropertiesScan            // finds @ConfigurationProperties classes in this package tree
public class ShopApplication { ... }

@Service
public class MailService {
    private final MailProperties mail;
    public MailService(MailProperties mail) { this.mail = mail; }   // injected like any bean
}

What you get:

  • One place for a group of settings, with real types (int, boolean, Duration, List, enums, nested records).
  • Relaxed binding: max-retries, maxRetries, max_retries and SHOP_MAIL_MAXRETRIES all bind to maxRetries.
  • Conversion: Duration accepts 10s, 500ms, 2m, 1h or ISO-8601 PT10S; DataSize accepts 10MB; lists accept comma-separated values or indexed YAML.
  • Defaults with @DefaultValue (for constructor binding) and validation with Jakarta Bean Validation when the class is @Validated and the validation starter is present. Invalid configuration stops the application at startup with a clear message, instead of failing on the first email at 3 a.m.
  • IDE completion for your own keys if you add the spring-boot-configuration-processor annotation processor.

Here is a simplified binder that does what Boot's does: it walks the record's components, derives the kebab-case key for each, converts the text to the component's type (including Duration with Boot's suffixes), applies defaults and validates. The second binding is deliberately broken and fails the way a Boot startup would.

Java Binding properties to a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real binder is much richer (nested objects, maps, enums, DataSize, constructor or setter binding), but the workflow is the same: find keys under the prefix, convert, default, validate, and fail before the application serves traffic. All three problems in the broken configuration are reported at once.

Profiles

A profile is a named set of configuration that is active only in some environments: dev, test, prod, or feature-specific names like h2 or kafka. Activate profiles with the spring.profiles.active property, which, like any property, can come from the command line or an environment variable:

Terminal
java -jar shop.jar --spring.profiles.active=prod
SPRING_PROFILES_ACTIVE=prod java -jar shop.jar

Profiles affect configuration in two ways.

Profile-specific files. application-{profile}.properties (or .yml) is loaded on top of application.properties when that profile is active, so it overrides matching keys and adds new ones. If several profiles are active, the one listed last wins for conflicting keys. In YAML you can also keep everything in one file, separating documents with ---:

YAML
shop:
  mail:
    host: localhost
---
spring:
  config:
    activate:
      on-profile: prod
shop:
  mail:
    host: smtp.example.com

Profile-specific beans. @Profile on a @Component or @Bean method registers it only when the expression matches:

Java
public interface MailSender { void send(String to, String text); }

@Component @Profile("dev")
class ConsoleMailSender implements MailSender { ... }      // prints mails instead of sending

@Component @Profile("!dev")
class SmtpMailSender implements MailSender { ... }         // every other environment

Expressions support !, & and |, for example @Profile("prod & !eu"). If no profile is active, Boot uses the default profile. You can also define profile groups: spring.profiles.group.local=dev,h2 makes --spring.profiles.active=local activate both.

The next program loads a base file plus profile files, merges them for different active profiles, and chooses a bean by @Profile, just like the container does at startup.

Java Profiles: files and beans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three runs, one code base: local expands to dev and h2, prod swaps the database and mail host, and prod,eu shows that the later profile wins the conflict over shop.mail.host.

Keep profiles few and meaningful. A common setup: application.properties holds safe defaults that work for local development, a test profile is used by automated tests, and production values come from environment variables set by the platform rather than from a prod file inside the JAR. That way, the JAR doesn't know production URLs or secrets at all.

Secrets and extra config files

Never commit passwords, API keys or tokens to application.properties. Options, from simplest to most robust:

  • Environment variables set by the deployment platform (SPRING_DATASOURCE_PASSWORD).

  • Imported files that live outside the repository:

    PROPERTIES
    spring.config.import=optional:file:./secrets.properties
    

    optional: means "fine if missing". Kubernetes and Docker secrets mounted as files work with configtree:: spring.config.import=optional:configtree:/run/secrets/ turns each file name into a key and its content into the value.

  • A secret store such as HashiCorp Vault or a cloud secret manager, integrated through Spring Cloud.

Also keep secrets out of logs: Actuator's /env endpoint masks values by default, but your own log.info("Config: " + props) doesn't. Override toString() on properties records that hold secrets.

Debugging configuration

When a value isn't what you expect:

  • Check the spelling and prefix. With @ConfigurationProperties, the configuration processor gives IDE warnings for unknown keys.
  • Look at /actuator/env/{key} (with Actuator) or log environment.getPropertySources() to see which source supplied the value.
  • Remember the order: an old environment variable (SERVER_PORT set months ago in your shell) silently beats your file.
  • Check active profiles: Boot logs "The following 1 profile is active: "dev"" at startup.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. application.properties in the JAR has server.port=8080, the environment has SERVER_PORT=8081, and the app starts with --server.port=8082. Which port is used?

    Command-line arguments have the highest priority, then environment variables, then files inside the JAR.
  2. 2. Which environment variable sets the property shop.mail.max-retries?

    Relaxed binding for environment variables: uppercase, dots become underscores and dashes are removed.
  3. 3. Profiles dev and eu are both active (in that order) and both files set shop.mail.host. Which value wins?

    Profile-specific files override the base file, and among active profiles the later one wins for the same key.
  4. 4. A @ConfigurationProperties record has a Duration timeout and the configuration says timeout=30. What is the result?

    Boot's Duration conversion treats a plain number as milliseconds by default. Write 30s to be explicit, or use @DurationUnit.
  5. 5. Why is @ConfigurationProperties with @Validated better than many @Value fields for a group of mail settings?

    Type-safe binding groups related settings, converts types and fails fast on invalid values, instead of scattering string keys.

Summary

  • Settings live in application.properties or application.yml; use kebab-case keys and your own prefix for app settings.
  • Boot searches property sources in order: command line, system properties, environment variables, external files, then files in the JAR. The first match wins.
  • Environment variables use relaxed names: SPRING_DATASOURCE_URL for spring.datasource.url.
  • ${key:default} placeholders reference other properties; missing required values fail at startup.
  • Use @Value for one-off values and @ConfigurationProperties records (with @DefaultValue and @Validated) for groups of settings; Duration, DataSize and lists are converted for you.
  • Profiles add application-{profile} files and @Profile beans; activate them with spring.profiles.active; the last active profile wins conflicts; groups bundle profiles.
  • Keep secrets out of the JAR and the repository: environment variables, spring.config.import, config trees or a secret store.

Next: Building REST APIs with Spring Boot puts this configured application to work with @RestController endpoints.