Spring Boot configuration: where values come from and how to bind them

A Spring Boot application reads every setting from one Environment built from many sources. This page shows the order of those sources running, binds values with @Value and with @ConfigurationProperties records, and covers environment variables, YAML, imports, validation and the mistakes that silently bind nothing.

Contents

How Spring Boot assembles its configuration

Every value a Spring Boot application reads, from server.port to your own app.max-retries, comes from one object: the Environment. It is not a single file. It is an ordered list of property sources, and a lookup asks each source in turn and takes the first value it finds.

Spring Boot fills that list before any of your beans exist. It adds command-line arguments, Java system properties, operating system environment variables and the JSON in SPRING_APPLICATION_JSON, and then loads the config data files: application.properties, application.yaml, their profile-specific variants, and anything they import. Because the same key can appear in several sources, the order decides which one wins. The reference documentation lists the sources from lowest to highest precedence; the most common ones are:

Common property sources, lowest precedence first
SourceTypical use
Default properties (SpringApplication.setDefaultProperties)Fallbacks set in code
@PropertySource on a configuration classLoading an extra file in plain Spring style
Config data: application.properties and .yamlThe application's normal settings
OS environment variablesContainers, Kubernetes, CI pipelines
Java system properties (-Dkey=value)JVM launch scripts
SPRING_APPLICATION_JSONMany settings in one environment variable
Command-line arguments (--key=value)One-off overrides
Test properties (@SpringBootTest(properties = ...), @TestPropertySource)Tests

Reading the values is the second half. @Value("${key}") injects one value into a field or parameter. @ConfigurationProperties binds a whole group of keys with a common prefix onto a typed object, such as a record. Both convert text into the target type, so 10s becomes a Duration and 5MB a DataSize.

The programs on this page run Spring Boot 4.1.2 without a web server. Each one writes its configuration files into a temporary folder and puts that folder on the classpath through a URLClassLoader, so the files load exactly as they would from src/main/resources in a packaged application. Records bound through their constructor need the -parameters compiler flag, which Spring Boot's Maven and Gradle plugins add for you; the programs here were compiled with it.

Which value wins, shown running

The key app.greeting is set in five places at once, so the output shows the whole order. The two other keys exist in only one source each:

Java
package props.precedence;

import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.env.PropertySource;

@SpringBootApplication
public class PropertyPrecedence {

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), """
                spring.main.banner-mode=off
                logging.level.root=WARN
                app.greeting=from application.properties
                app.region=eu-west-1
                """);
        System.setProperty("app.greeting", "from a system property");
        System.setProperty("spring.application.json",
                "{\"app\":{\"greeting\":\"from spring.application.json\"}}");

        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                PropertyPrecedence.class.getClassLoader());
        SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
                PropertyPrecedence.class);
        app.setDefaultProperties(Map.of(
                "app.greeting", "from default properties",
                "app.timeout", "30s"));
        String[] commandLine = {"--app.greeting=from the command line"};

        try (ConfigurableApplicationContext context = app.run(commandLine)) {
            ConfigurableEnvironment env = context.getEnvironment();
            System.out.println("app.greeting = " + env.getProperty("app.greeting"));
            System.out.println("app.region   = " + env.getProperty("app.region"));
            System.out.println("app.timeout  = " + env.getProperty("app.timeout"));
            System.out.println();
            System.out.println("Property sources, highest precedence first:");
            for (PropertySource<?> source : env.getPropertySources()) {
                Object value = source.getProperty("app.greeting");
                System.out.println("  " + source.getName()
                        + (value == null ? "" : "\n      app.greeting=" + value));
            }
        }
    }
}
Output
app.greeting = from the command line
app.region   = eu-west-1
app.timeout  = 30s

Property sources, highest precedence first:
  configurationProperties
      app.greeting=from the command line
  commandLineArgs
      app.greeting=from the command line
  spring.application.json
      app.greeting=from spring.application.json
  systemProperties
      app.greeting=from a system property
  systemEnvironment
  random
  Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'
      app.greeting=from application.properties
  applicationInfo
  defaultProperties
      app.greeting=from default properties
  • app.greeting came from the command line, the highest source in the list. Every lower source still holds its own value; nothing is overwritten, the lookup simply stops at the first match.
  • app.region exists only in application.properties and app.timeout only in the default properties, so each was found further down the list.
  • The first source, configurationProperties, is not a real source. Spring Boot attaches it as a view over all the others, which is how relaxed names such as APP_GREETING can match app.greeting.
  • spring.application.json came from the system property of that name and sits above ordinary system properties. The SPRING_APPLICATION_JSON environment variable is read the same way.
  • random serves ${random.uuid}, ${random.int} and similar values, and applicationInfo holds spring.application.pid and spring.application.version.
  • The config file appears as class path resource [application.properties], found through the default location optional:classpath:/. The optional: prefix is why an application with no application.properties still starts.

Within config data, a profile-specific file such as application-prod.properties overrides application.properties, and a file outside the jar overrides one inside it. Spring Boot looks in the classpath root, the classpath /config package, the current directory, the config/ folder in the current directory and its immediate child folders, with later locations overriding earlier ones. The profiles page shows the profile-specific files at work.

@Value: one value, with defaults and SpEL

A mail client needs a host, a port, a timeout, a size limit and a list of recipients, so one bean shows each kind of conversion. The file leaves out the port and the sender to show both kinds of default:

Java
package props.value;

import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;

@SpringBootApplication
public class ValueInjection {

    @Component
    static class MailSettings {
        @Value("${mail.host}")
        String host;

        @Value("${mail.port:25}")
        int port;

        @Value("${mail.timeout}")
        Duration timeout;

        @Value("${mail.max-attachment}")
        DataSize maxAttachment;

        @Value("${mail.recipients}")
        List<String> recipients;

        @Value("${mail.sender:no-reply@${mail.domain}}")
        String sender;

        @Value("#{${mail.port:25} == 465 ? 'SMTPS' : 'SMTP'}")
        String protocol;

        @Value("#{'${mail.host}'.toUpperCase()}")
        String hostUpper;
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), """
                spring.main.banner-mode=off
                logging.level.root=WARN
                mail.host=smtp.example.com
                mail.domain=example.com
                mail.timeout=10s
                mail.max-attachment=5MB
                mail.recipients=ops@example.com, dev@example.com
                """);
        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                ValueInjection.class.getClassLoader());
        SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
                ValueInjection.class);
        try (var context = app.run(args)) {
            MailSettings mail = context.getBean(MailSettings.class);
            System.out.println("host          = " + mail.host);
            System.out.println("port          = " + mail.port + "   (default after the colon)");
            System.out.println("timeout       = " + mail.timeout + " = "
                    + mail.timeout.toMillis() + " ms");
            System.out.println("maxAttachment = " + mail.maxAttachment + " = "
                    + mail.maxAttachment.toBytes() + " bytes");
            System.out.println("recipients    = " + mail.recipients + " (size "
                    + mail.recipients.size() + ")");
            System.out.println("sender        = " + mail.sender);
            System.out.println("protocol      = " + mail.protocol);
            System.out.println("hostUpper     = " + mail.hostUpper);
        }
    }
}
Output
host          = smtp.example.com
port          = 25   (default after the colon)
timeout       = PT10S = 10000 ms
maxAttachment = 5242880B = 5242880 bytes
recipients    = [ops@example.com, dev@example.com] (size 2)
sender        = no-reply@example.com
protocol      = SMTP
hostUpper     = SMTP.EXAMPLE.COM
  • ${mail.port:25} had no value in the file, so the text after the colon, 25, was converted to an int.
  • 10s became PT10S, a Duration of 10000 ms. A bare number would have meant milliseconds.
  • 5MB became 5242880 bytes. Spring's DataSize uses binary units, so one megabyte is 1024 times 1024 bytes, not one million.
  • The comma-separated recipients became a List of 2 elements, with the space after the comma trimmed.
  • A default can contain another placeholder: ${mail.sender:no-reply@${mail.domain}} resolved to no-reply@example.com.
  • #{...} is a SpEL expression evaluated after the ${...} placeholders inside it were replaced, which produced SMTP and the upper-case host.

@Value suits a single setting in one class. Once several classes read the same group of keys, the key names are repeated as strings across the code base, and a typo in one of them is found only when that bean starts.

@ConfigurationProperties: typed groups of settings

A shop's settings include a number, a duration, a size, a list, a map, a list of objects and a nested group. Binding them onto one record shows how each shape is written in a properties file:

Java
package props.typed;

import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.util.unit.DataSize;

@SpringBootApplication
@ConfigurationPropertiesScan
public class TypedProperties {

    @ConfigurationProperties("shop")
    public record ShopProperties(
            String name,
            @DefaultValue("3") int maxRetries,
            @DurationUnit(ChronoUnit.SECONDS) Duration cacheTtl,
            DataSize maxUpload,
            List<String> currencies,
            Map<String, Integer> stockLimits,
            List<Warehouse> warehouses,
            @DefaultValue Payment payment) {

        public record Warehouse(String code, String city) {
        }

        public record Payment(@DefaultValue("stripe") String provider,
                @DefaultValue("5s") Duration timeout) {
        }
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), """
                spring.main.banner-mode=off
                logging.level.root=WARN
                shop.name=Corner Books
                shop.cache-ttl=90
                shop.max-upload=2MB
                shop.currencies=GBP,EUR
                shop.stock-limits.books=500
                shop.stock-limits.maps=40
                shop.warehouses[0].code=LON
                shop.warehouses[0].city=London
                shop.warehouses[1].code=MAN
                shop.warehouses[1].city=Manchester
                """);
        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                TypedProperties.class.getClassLoader());
        SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
                TypedProperties.class);
        try (var context = app.run(args)) {
            ShopProperties shop = context.getBean(ShopProperties.class);
            System.out.println("name        = " + shop.name());
            System.out.println("maxRetries  = " + shop.maxRetries() + "  (from @DefaultValue)");
            System.out.println("cacheTtl    = " + shop.cacheTtl() + "  (90 read as seconds)");
            System.out.println("maxUpload   = " + shop.maxUpload());
            System.out.println("currencies  = " + shop.currencies());
            System.out.println("stockLimits = " + shop.stockLimits());
            shop.warehouses().forEach(w -> System.out.println("warehouse   = " + w));
            System.out.println("payment     = " + shop.payment());
            System.out.println("bean name   = "
                    + context.getBeanNamesForType(ShopProperties.class)[0]);
        }
    }
}
Output
name        = Corner Books
maxRetries  = 3  (from @DefaultValue)
cacheTtl    = PT1M30S  (90 read as seconds)
maxUpload   = 2097152B
currencies  = [GBP, EUR]
stockLimits = {books=500, maps=40}
warehouse   = Warehouse[code=LON, city=London]
warehouse   = Warehouse[code=MAN, city=Manchester]
payment     = Payment[provider=stripe, timeout=PT5S]
bean name   = shop-props.typed.TypedProperties$ShopProperties
  • The file uses kebab-case (cache-ttl, stock-limits) and the record uses camelCase. Relaxed binding matched them without any mapping.
  • maxRetries was not in the file, so @DefaultValue("3") supplied it. Without the annotation a missing int would be 0.
  • shop.cache-ttl=90 became 1 minute 30 seconds, because @DurationUnit(ChronoUnit.SECONDS) changed the unit for bare numbers from milliseconds to seconds.
  • shop.stock-limits.books=500 created a map entry, and shop.warehouses[0].code the first element of a list of records.
  • No shop.payment keys exist, yet payment is not null: the empty @DefaultValue on the parameter asks Spring Boot to create the nested record anyway, and its own defaults filled in stripe and 5 seconds.
  • The bean is named shop- followed by the class name. @ConfigurationPropertiesScan found the record and registered it, which constructor binding requires; a @Component or @Bean would not bind a record through its constructor.
@ConfigurationProperties compared with @Value
Feature@ConfigurationProperties@Value
Relaxed bindingYesLimited: write the key in kebab-case
Lists, maps and nested objectsYesComma-separated lists only
Bean Validation with @ValidatedYesNo
IDE completion through generated metadataYes, with spring-boot-configuration-processorNo
SpEL expressionsNoYes

Environment variables and relaxed binding

Containers and Kubernetes pass settings as environment variables, which cannot contain dots or dashes. The program starts a second JVM with four variables set, because a running JVM cannot change its own environment:

Java
package props.env;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class EnvVarBinding {

    @ConfigurationProperties("app")
    public record AppProperties(int maxRetries, String regionName, List<String> servers) {
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            launchChild();
            return;
        }
        try (var context = SpringApplication.run(EnvVarBinding.class, args)) {
            AppProperties app = context.getBean(AppProperties.class);
            System.out.println("  maxRetries = " + app.maxRetries());
            System.out.println("  regionName = " + app.regionName());
            System.out.println("  servers    = " + app.servers());
            System.out.println("  @Value-style lookup of app.max-retries: "
                    + context.getEnvironment().getProperty("app.max-retries"));
        }
    }

    /** Starts this class again in a new JVM, with environment variables set. */
    static void launchChild() throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), """
                spring.main.banner-mode=off
                logging.level.root=WARN
                app.max-retries=3
                app.region-name=eu-west-1
                app.servers=a.example.com,b.example.com
                """);
        String java = ProcessHandle.current().info().command().orElseThrow();
        ProcessBuilder child = new ProcessBuilder(java,
                "-cp", dir + File.pathSeparator + System.getProperty("java.class.path"),
                EnvVarBinding.class.getName(), "child");
        child.environment().put("APP_MAXRETRIES", "7");
        child.environment().put("APP_REGIONNAME", "us-east-2");
        child.environment().put("APP_SERVERS_0", "c.example.com");
        child.environment().put("APP_SERVERS_1", "d.example.com");
        child.environment().remove("JAVA_TOOL_OPTIONS");
        child.inheritIO();
        System.out.println("application.properties says max-retries=3, region-name=eu-west-1,"
                + " servers=a,b");
        System.out.println("Environment: APP_MAXRETRIES=7 APP_REGIONNAME=us-east-2"
                + " APP_SERVERS_0=c... APP_SERVERS_1=d...");
        System.out.println("Bound values:");
        System.out.flush();
        int exit = child.start().waitFor();
        System.out.println("child exit code " + exit);
    }
}
Output
application.properties says max-retries=3, region-name=eu-west-1, servers=a,b
Environment: APP_MAXRETRIES=7 APP_REGIONNAME=us-east-2 APP_SERVERS_0=c... APP_SERVERS_1=d...
Bound values:
  maxRetries = 7
  regionName = us-east-2
  servers    = [c.example.com, d.example.com]
  @Value-style lookup of app.max-retries: 7
child exit code 0
  • APP_MAXRETRIES=7 overrode app.max-retries=3 from the file. To get the variable name, replace dots with underscores, remove dashes and use upper case.
  • APP_SERVERS_0 and APP_SERVERS_1 replaced the whole list: the two servers from the file are gone, not merged. A number between underscores is a list index.
  • getProperty("app.max-retries") also returned 7. Lookups through the Environment, and therefore @Value, match environment variables as long as the key is written in its canonical kebab-case form.

The documented rule removes dashes, but Spring Boot also accepts the form with each dash turned into an underscore: run with APP_MAX_RETRIES=9 instead, this program binds 9 as well. Lists bound from variables are replaced as a whole, so a single APP_SERVERS_0 leaves a one-element list.

YAML files and spring.config.import

YAML suits nested settings and lists of objects. This program puts an application.yaml and an application.properties in the same folder, both setting feeds.owner, and imports one file that exists and one that does not:

Java
package props.yaml;

import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;

@SpringBootApplication
@ConfigurationPropertiesScan
public class YamlAndImport {

    @ConfigurationProperties("feeds")
    public record FeedProperties(String owner, List<Feed> sources) {
        public record Feed(String name, String url, int everyMinutes) {
        }
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.yaml"), """
                spring:
                  main:
                    banner-mode: off
                  config:
                    import:
                      - classpath:feeds-secrets.properties
                      - optional:file:./does-not-exist.properties
                logging:
                  level:
                    root: WARN
                feeds:
                  owner: yaml-owner
                  sources:
                    - name: news
                      url: https://example.com/news.xml
                      every-minutes: 15
                    - name: weather
                      url: https://example.com/weather.xml
                      every-minutes: 60
                """);
        Files.writeString(dir.resolve("application.properties"), """
                feeds.owner=properties-owner
                """);
        Files.writeString(dir.resolve("feeds-secrets.properties"), """
                feeds.api-token=t0k3n
                """);
        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                YamlAndImport.class.getClassLoader());
        SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
                YamlAndImport.class);
        try (var context = app.run(args)) {
            FeedProperties feeds = context.getBean(FeedProperties.class);
            System.out.println("owner = " + feeds.owner());
            feeds.sources().forEach(f -> System.out.println("feed  = " + f));
            System.out.println("token = "
                    + context.getEnvironment().getProperty("feeds.api-token"));
            System.out.println("Config data sources:");
            for (PropertySource<?> source : context.getEnvironment().getPropertySources()) {
                if (source.getName().startsWith("Config resource")) {
                    System.out.println("  " + source.getName());
                }
            }
        }
    }
}
Output
owner = properties-owner
feed  = Feed[name=news, url=https://example.com/news.xml, everyMinutes=15]
feed  = Feed[name=weather, url=https://example.com/weather.xml, everyMinutes=60]
token = t0k3n
Config data sources:
  Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'
  Config resource 'class path resource [feeds-secrets.properties]' via location 'classpath:feeds-secrets.properties'
  Config resource 'class path resource [application.yaml]' via location 'optional:classpath:/'
  • The two feeds were read from the YAML list, with every-minutes bound to everyMinutes.
  • owner is properties-owner. When both formats sit in the same location, the .properties file takes precedence, as the source order at the end shows.
  • The imported feeds-secrets.properties supplied the token. An import is inserted directly below the document that declares it, here just above application.yaml.
  • The missing optional:file:./does-not-exist.properties was skipped silently. Without optional:, startup fails with ConfigDataLocationNotFoundException.

Use one format per application to avoid that precedence question. spring.config.import is also how Spring Cloud Config, Vault and Kubernetes config trees join the Environment, using prefixes such as configserver: or configtree:. Properties files are read as ISO-8859-1 by default; add [encoding=utf-8] to an import to change that.

Validating settings at startup

A wrong setting should stop the application at startup, not cause a failure hours later. Adding @Validated and Bean Validation constraints does that; here the retry limit is set to 50 where the maximum is 10:

Java
package props.validated;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.validation.annotation.Validated;

@SpringBootApplication
@ConfigurationPropertiesScan
public class ValidatedProperties {

    @Validated
    @ConfigurationProperties("payment")
    public record PaymentProperties(
            @NotBlank String apiKey,
            @Min(1) @Max(10) int maxRetries,
            @Valid Callback callback) {

        public record Callback(@Pattern(regexp = "https://.*") String url) {
        }
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), """
                spring.main.banner-mode=off
                logging.level.root=WARN
                logging.pattern.console=%m%n
                payment.api-key=sk_test_123
                payment.max-retries=50
                payment.callback.url=https://shop.example.com/paid
                """);
        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                ValidatedProperties.class.getClassLoader());
        SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
                ValidatedProperties.class);
        try {
            app.run(args).close();
        } catch (RuntimeException e) {
            System.out.println("run() threw " + e.getClass().getSimpleName());
        }
    }
}
Output
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'payment-props.validated.ValidatedProperties$PaymentProperties': Could not bind properties to 'ValidatedProperties.PaymentProperties' : prefix=payment, ignoreInvalidFields=false, ignoreUnknownFields=true


***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target props.validated.ValidatedProperties$PaymentProperties failed:

    Property: payment.maxRetries
    Value: "50"
    Origin: class path resource [application.properties] - 5:21
    Reason: must be less than or equal to 10


Action:

Update your application's configuration

run() threw ConfigurationPropertiesBindException
  • The application did not start. run() threw ConfigurationPropertiesBindException while the bean was being created.
  • Spring Boot's failure analyzer printed the report: the property payment.maxRetries, its value "50", the reason, and the origin class path resource [application.properties] - 5:21, which is the line and column of the value.
  • @Valid on callback extends validation to the nested record. Its URL starts with https://, so it passed.

Validation needs a Bean Validation implementation on the classpath, which spring-boot-starter-validation provides with Hibernate Validator. Without one, @Validated on configuration properties is not enforced. When several constraints fail, all of them are listed, in no fixed order.

Traps that bind nothing

Configuration mistakes rarely fail loudly. This program runs three common ones, two of which start without any error:

Java
package props.traps;

import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

@SpringBootApplication
@ConfigurationPropertiesScan
public class PropertyTraps {

    @ConfigurationProperties("orders")
    public record OrderProperties(int maxItems, boolean expressShipping) {
    }

    @Component
    static class Holder {
        @Value("${orders.max-items}")
        static int staticMaxItems;

        @Value("${orders.max-items}")
        int instanceMaxItems;
    }

    static class NotABean {
        @Value("${orders.max-items}")
        int maxItems;
    }

    static SpringApplication app(String properties) throws Exception {
        Path dir = Files.createTempDirectory("config");
        Files.writeString(dir.resolve("application.properties"), properties);
        var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
                PropertyTraps.class.getClassLoader());
        return new SpringApplication(new DefaultResourceLoader(resources), PropertyTraps.class);
    }

    public static void main(String[] args) throws Exception {
        String base = """
                spring.main.banner-mode=off
                logging.level.root=OFF
                orders.max-items=20
                orders.express-shiping=true
                """;
        try (var context = app(base).run(args)) {
            OrderProperties orders = context.getBean(OrderProperties.class);
            System.out.println("1. Misspelt key orders.express-shiping=true:");
            System.out.println("   expressShipping = " + orders.expressShipping());
            System.out.println("2. @Value on a static field and on a new object:");
            System.out.println("   static field   = " + Holder.staticMaxItems);
            System.out.println("   instance field = "
                    + context.getBean(Holder.class).instanceMaxItems);
            System.out.println("   new NotABean() = " + new NotABean().maxItems);
        }

        System.out.println("3. @Value for a property that is not defined:");
        try {
            SpringApplication strict = app(base);
            strict.addPrimarySources(List.of(NeedsRegion.class));
            strict.run(args).close();
        } catch (RuntimeException e) {
            Throwable root = e;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            System.out.println("   startup failed: " + root.getMessage());
        }
    }

    /** Not a @Component, so only the third run registers it. */
    static class NeedsRegion {
        @Value("${orders.region}")
        String region;
    }
}
Output
1. Misspelt key orders.express-shiping=true:
   expressShipping = false
2. @Value on a static field and on a new object:
   static field   = 0
   instance field = 20
   new NotABean() = 0
3. @Value for a property that is not defined:
   startup failed: Could not resolve placeholder 'orders.region' in value "${orders.region}"
  • The misspelt orders.express-shiping=true matched no field, so expressShipping stayed false and nothing was reported. @ConfigurationProperties ignores unknown keys by default. The configuration processor's metadata lets the IDE flag such typos, and ignoreUnknownFields = false turns them into startup errors.
  • The static field stayed 0. Spring injects into objects, not classes, and skips static fields. Inject into an instance field or a constructor instead.
  • new NotABean() also got 0, because Spring never saw the object. @Value works only on beans that Spring creates.
  • A ${orders.region} placeholder with no value and no default stopped startup with Could not resolve placeholder. This one at least fails early; give a default (${orders.region:eu}) when the value is optional.

Two more are worth knowing. Keys in a file loaded by @PropertySource arrive too late for logging.* and spring.main.*, which are read before the context starts. And secrets in application.properties end up in the jar and in version control; pass them as environment variables or through an import from a secret store.

Choosing how to configure

Situations and the configuration style that fits them
SituationUse
A group of related settings used by your codeA record with @ConfigurationProperties and @ConfigurationPropertiesScan
One value in one class@Value("${key:default}")
A value computed from other values@Value with a SpEL expression
Settings that must be correct before the application runs@Validated with Bean Validation constraints
Values that differ per environmentProfile-specific files or environment variables
SecretsEnvironment variables, or spring.config.import from a secret store
A one-off override when starting the jar--key=value on the command line
Deeply nested settings or lists of objectsapplication.yaml

For values that change between development, test and production, continue with Spring Boot profiles. The logging page shows the logging.* keys, and dependency injection explains how Spring creates the beans these values are injected into.