Spring Boot & Spring Cloud

Spring Boot Configuration: Properties, YAML, Profiles and @ConfigurationProperties

Beginner8 min readUpdated

You will be able to configure a Spring Boot 3 service for several environments without rebuilding it: choose between properties and YAML, understand which source wins when values conflict, activate profiles correctly, bind settings to validated, immutable configuration classes, and keep secrets out of the jar.

What you will learn

  • Rank Spring Boot's property sources and predict which value wins when the same key is set twice
  • Write profile-specific configuration with application-{profile} files and multi-document YAML
  • Bind configuration to immutable, validated @ConfigurationProperties records
  • Use relaxed binding so that environment variables, YAML keys and command-line arguments map to the same property
  • Import external configuration files and keep credentials out of the packaged artifact

A service that must be rebuilt to change a port, a database URL or a feature flag cannot be promoted from staging to production as the same artifact, and the same artifact is the whole point of a deployment pipeline. Spring Boot's answer is externalised configuration: one immutable jar, many property sources layered on top of each other at startup, with a defined order for resolving conflicts. This page covers that order, the file formats, profiles, type-safe binding, and the habits that keep configuration from turning into a debugging exercise.

Where properties come from

Boot builds a single Environment from many PropertySources. When the same key appears in several of them, the one with the higher precedence wins. The list below is ordered from lowest to highest precedence and includes the sources you will meet in practice (the reference documentation has the complete list):

  1. Default properties set programmatically with SpringApplication.setDefaultProperties
  2. @PropertySource annotations on @Configuration classes
  3. Config data files: application.properties / application.yml, then profile-specific variants
  4. A RandomValuePropertySource (random.int, random.uuid)
  5. OS environment variables
  6. Java system properties (-Dserver.port=9090)
  7. JNDI attributes, servlet context and servlet config parameters
  8. SPRING_APPLICATION_JSON (inline JSON in an environment variable or system property)
  9. Command-line arguments (--server.port=9090)
  10. properties on @SpringBootTest, @TestPropertySource and @DynamicPropertySource in tests
  11. DevTools global settings on the developer machine

Two consequences are worth internalising. First, anything set on the command line or in the environment beats anything inside the jar, which is exactly what an operator needs. Second, @PropertySource is loaded so late in the process that it cannot influence early decisions such as logging setup or spring.profiles.active; it is a compatibility feature, not the primary mechanism.

Within the config-data layer, files are also ordered. Boot looks for application.* in these locations, later ones overriding earlier:

  1. the classpath root
  2. the /config package on the classpath
  3. the current working directory
  4. a /config subdirectory of the working directory, and immediate children of it

So a file dropped next to the jar at ./config/application.yml overrides the one packaged inside, without any flag. spring.config.name changes the base name and spring.config.location replaces the search path entirely (spring.config.additional-location adds to it). Both must be given early, as command-line arguments or environment variables, because they are read before the files are.

Properties versus YAML

The two formats express the same tree. Compare:

server.port=8081
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.jpa.open-in-view=false
app.allowed-origins[0]=https://shop.example.com
app.allowed-origins[1]=https://admin.example.com
server:
  port: 8081
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
  jpa:
    open-in-view: false
app:
  allowed-origins:
    - https://shop.example.com
    - https://admin.example.com

YAML wins on readability once nesting and lists appear, and it allows several documents in one file separated by ---. Its costs are indentation sensitivity and a few parsing surprises: unquoted yes/no/on/off become booleans in some YAML parsers, 01 may be read as an octal number, and a value containing a colon must be quoted. Boot uses SnakeYAML and requires it on the classpath; the starters include it. Note also that YAML files cannot be loaded through @PropertySource.

Placeholders work in both: app.base-url=https://${app.host}:${server.port} resolves against the whole Environment, and ${MY_VAR:default} supplies a fallback.

Profiles

A profile is a named slice of configuration and beans. Activate one or more with spring.profiles.active=prod (property, environment variable SPRING_PROFILES_ACTIVE, or --spring.profiles.active=prod). When no profile is active, the default profile is.

Profile-specific files follow the application-{profile}.yml naming convention, live in the same locations as application.yml, and override it. If several profiles are active, the last one listed wins. The same effect can be achieved inside a single YAML file:

spring:
  application:
    name: shop
  jpa:
    open-in-view: false
---
spring:
  config:
    activate:
      on-profile: local
  datasource:
    url: jdbc:h2:mem:shop
logging:
  level:
    org.hibernate.SQL: DEBUG
---
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:postgresql://db.internal:5432/shop
server:
  shutdown: graceful

The spring.config.activate.on-profile key replaced the older spring.profiles key in Boot 2.4. Profile expressions are allowed: on-profile: "prod & eu" or "!local".

Profiles also gate beans. @Profile("local") on a @Configuration or @Bean registers it only when that profile is active; @Profile("!prod") is the usual way to keep a fake payment gateway out of production. Keep this sparing: a service whose bean graph differs wildly between environments is a service you have not really tested before deploying it.

Profile groups let one profile expand into several: spring.profiles.group.prod=prod-db,prod-mq means activating prod also activates the two others. spring.profiles.include adds profiles unconditionally. Neither may appear in a profile-specific document, for the ordering reason explained in the FAQ.

A common and sensible layout: a base application.yml with everything shared, one small profile file per environment holding only what differs, all committed to version control, and secrets supplied from outside (see below). Environment names such as local, test, staging and prod are conventions, not keywords; Boot only cares about the string.

Type-safe binding with @ConfigurationProperties

@Value("${app.timeout}") works for one or two settings. Beyond that it scatters string keys across the code base, offers no validation and no IDE support. @ConfigurationProperties binds a whole prefix to an object:

package com.example.shop.config;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import java.time.Duration;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.validation.annotation.Validated;

@Validated
@ConfigurationProperties(prefix = "app")
public record AppProperties(
        @NotEmpty List<String> allowedOrigins,
        @Positive int maxPageSize,
        Duration requestTimeout,        // "30s", "2m", "500ms" all bind
        Catalog catalog) {

    public record Catalog(boolean cacheEnabled, Duration cacheTtl) {}
}

Registering it takes one of two annotations on a configuration class: @EnableConfigurationProperties(AppProperties.class) for explicit control, or @ConfigurationPropertiesScan on the application class to pick up every annotated class in the package tree. Inject AppProperties wherever you need it like any other bean.

Records give you constructor binding and immutability for free. In Boot 3 a record, or a class with a single parameterised constructor, is bound through its constructor automatically; the explicit @ConstructorBinding annotation from Boot 2 is only needed when a class has several constructors. A mutable JavaBean with setters still works when you need defaults that depend on other values, but records should be the default choice.

@Validated switches on Jakarta Bean Validation for the bound object, so a missing allowedOrigins fails at startup with a clear message listing the rejected value and the constraint. Failing early beats discovering a typo in a property name on the first production request.

Add the spring-boot-configuration-processor as an optional dependency (annotationProcessor in Gradle) and the build generates META-INF/spring-configuration-metadata.json, which is what gives you completion and documentation for your own keys in IntelliJ IDEA, Eclipse and VS Code. Javadoc on the record components becomes the description shown in the IDE.

Relaxed binding

Boot normalises key names so that one property can be written in the style natural to each source:

SourceSpelling of app.max-page-size
Properties / YAMLapp.max-page-size (kebab-case, canonical), also app.maxPageSize or app.max_page_size
Environment variableAPP_MAXPAGESIZE (upper case, dots to underscores, dashes removed)
System property / command lineapp.max-page-size or app.maxPageSize

For lists in environment variables, indices become numeric segments: APP_ALLOWEDORIGINS_0=https://shop.example.com. Relaxed binding applies to @ConfigurationProperties; @Value is stricter and expects the exact canonical name.

Conversion

Binding understands durations (10s, PT10S, or a plain number with @DurationUnit), data sizes (10MB, @DataSizeUnit), periods, enums (case-insensitive), File, Resource, InetAddress and any type with a String constructor or valueOf. Custom conversions register through a Converter bean annotated @ConfigurationPropertiesBinding.

Importing configuration and handling secrets

spring.config.import pulls additional sources into the config-data layer, processed after the file that declares them:

spring.config.import=optional:file:./overrides.properties,optional:configtree:/run/secrets/
  • file: and classpath: import ordinary property or YAML files.
  • optional: prevents a startup failure when the location is absent, which is what you want for a developer-only override file.
  • configtree: reads a directory where each file's name is the key and its content is the value, the layout Kubernetes and Docker produce when mounting secrets. A file /run/secrets/db-password becomes the property db-password.
  • configserver: (with Spring Cloud Config) and vault: (with Spring Cloud Vault) fetch from a central store.

None of these belong in the jar: not passwords, not API keys, not private certificates. Feed them through environment variables, mounted secret files or a config server, and reference them from application.yml with placeholders such as password: ${DB_PASSWORD}. If you must keep an encrypted value in a file, Spring Cloud Config's {cipher} prefix and Jasypt integrations exist, but a secret manager is the better tool.

Configuring logging through properties

Logging is the configuration most people touch first, and Boot exposes the common cases as properties so that a logback configuration file is rarely needed:

logging.level.root=INFO
logging.level.com.example.shop=DEBUG
logging.level.org.springframework.web=DEBUG
logging.file.name=/var/log/shop/app.log
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n
logging.logback.rollingpolicy.max-file-size=50MB

logging.file.name and logging.file.path replaced the pre-2.2 logging.file and logging.path keys; the old names still show up in tutorials and no longer work. Logback is the default implementation behind the starters; switching to Log4j2 is an exclusion of spring-boot-starter-logging plus spring-boot-starter-log4j2. Because logging is initialised before most of the context, logging.* properties must live in a config-data file, an environment variable or the command line; a @PropertySource is too late.

Common mistakes

Assuming the profile file adds to the list rather than replaces the value. Lists are replaced wholesale: an app.allowed-origins with two entries in application.yml and one entry in application-prod.yml yields one entry in production, not three. Maps, by contrast, are merged key by key.

Setting spring.profiles.active in application.yml and wondering why it cannot be overridden. It can: a command-line argument wins. The real problem is that a profile hard-coded inside the artifact is one more thing operators have to remember to override. Leave it unset in the packaged file and set it from the environment.

Using an inner class for properties without static. The binder cannot instantiate a non-static inner class; nested groups must be static nested classes or records.

Typo in a property name. Boot ignores unknown keys silently; server.prot=9090 does nothing. Enable ignore-unknown-fields = false on your own @ConfigurationProperties, rely on IDE metadata for Boot's keys, and prefer a small number of well-named prefixes.

Sending secrets through SPRING_APPLICATION_JSON or the command line. Both are visible to any process that can list arguments or read the environment of the JVM; mounted files with restricted permissions are safer on shared hosts.

Best practices

  • Commit application.yml and all application-{profile}.yml files; treat them as code with reviews and history. Keep the base file complete and the profile files minimal.
  • Bind related settings into one @ConfigurationProperties record per concern, validate it, and inject the record rather than individual @Value fields.
  • Choose the canonical kebab-case spelling for keys in files; it is what the metadata and documentation use.
  • Document every custom key with Javadoc so the generated metadata explains it in the IDE.
  • Keep the number of profiles small and their meaning obvious; if a profile is only ever activated together with another, use a group instead of asking everyone to remember the pair.
  • When behaviour differs between environments, prefer a property that a single bean reads over swapping beans with @Profile.

Key takeaways

  • Boot merges many property sources into one Environment; command-line arguments and environment variables override files inside the jar, and files next to the jar override packaged ones.
  • Properties and YAML are equivalent; YAML adds multi-document files and readability at the cost of indentation and parsing gotchas.
  • Profiles select configuration and beans; profile-specific files override the base file, and spring.profiles.active should be supplied from outside the artifact.
  • @ConfigurationProperties records with @Validated give immutable, type-safe, IDE-assisted configuration and fail fast on bad values.
  • Relaxed binding maps app.max-page-size, app.maxPageSize and APP_MAXPAGESIZE to the same key.
  • spring.config.import with optional: and configtree: is the clean way to bring in overrides and mounted secrets without touching the jar.

Sources and further reading

Frequently asked questions

Should I use application.properties or application.yml?
Both are fully supported and offer the same features. YAML is easier to read when you have nested keys and lists, and it supports several documents in one file, which is convenient for profile-specific sections. Properties files are flatter, harder to get wrong with indentation, and better supported by some tooling. Pick one per project; if both exist with the same name, the .properties file takes precedence.
Why is my environment variable not overriding application.yml?
Check the name first: SPRING_DATASOURCE_URL maps to spring.datasource.url through relaxed binding, but the segments must be joined with single underscores and any dashes in the property name removed. Then check the scope: the variable has to be visible to the JVM process itself, not just to your shell or to a Docker build step. Finally, remember that command-line arguments and test properties rank higher than environment variables.
Can I set spring.profiles.active inside a profile-specific file?
No. Boot rejects spring.profiles.active and spring.profiles.include in profile-specific files and in YAML documents activated by spring.config.activate.on-profile, because a profile that activates other profiles while it is being loaded would make the result order-dependent. Use spring.profiles.group in the main document instead to define a profile that expands into several others.
How do I see the final value of a property at runtime?
With Actuator, expose the env endpoint and query /actuator/env/your.property.name; it lists every property source that contains the key and which one won. In Boot 3 the values are masked by default; set management.endpoint.env.show-values=when-authorized (or always, only in a protected environment) to see them. For a one-off check, inject Environment and log getProperty in a CommandLineRunner.