Boot properties

Key idea
Spring Boot loads properties from many sources (`application.properties`/`.yml` files, profile-specific files, environment variables, system properties, arguments…) in a fixed precedence order, and `@ConfigurationProperties` pours them into an object with types, defaults and validation.
In the box
The box configuration was spread across dozens of @Value annotations with the prefix repeated and no validation. Group it into a record with @ConfigurationProperties, learn where Boot looks for properties and in which order, how profiles and relaxed binding work, and how to validate at startup.
ApplicationContextapplication.ymlEnvironmentValueBasedSettings

The Environment fills ValueBasedSettings, highlighted in red, with one @Value per property.

The application.yml file, outside the context and highlighted together with the Environment, is loaded at startup.

The Environment passes box.* to the Binder, which creates the BoxProperties; both are highlighted.

The Binder hands BoxProperties, highlighted, the value "60m" already converted into a Duration.

The Binder, highlighted, receives maxAthletes and binds it as if it were max-athletes.

application-prod.yml, highlighted, contributes max-athletes 20 to the Environment, beating application.yml.

The --box.max-athletes=40 argument, highlighted together with the Environment, beats the YAML files.

The Binder asks Bean Validation, highlighted, to check @Min(1); it fails and the application doesn't start.

Final view: the files and arguments outside, and the Environment, the Binder, BoxProperties with its validation and BoxInfoService inside the context.

Step 1 of 9

One @Value per property

ValueBasedSettings reads the box configuration with one @Value per property:

  • The box. prefix is repeated on every line, and a typo only shows up at startup (or worse, stays unresolved).
  • class-duration arrives as a String and has to be converted by hand.
  • Nobody checks that max-athletes makes sense.

Step 2 of 9

application.yml and where Boot looks for it

Spring Boot loads the application.properties or application.yml files on its own. It looks in classpath:/, classpath:/config/, the current directory and ./config/ (those outside the jar have higher priority).

box:
  name: CrossFit Norte
  max-athletes: 12
  class-duration: 60m
  plans: [monthly, ten-pack, drop-in]
  address:
    city: Madrid

YAML allows hierarchies and lists without repeating prefixes. To bring in more files, spring.config.import=optional:file:./secrets.yml.

Step 3 of 9

@ConfigurationProperties

BoxProperties is a record annotated with @ConfigurationProperties(prefix = "box"). Boot's Binder takes every box.* property and pours it into it by name:

  • box.name → name, box.max-athletes → maxAthletes…
  • Being a record, it binds through the constructor: an immutable object. A class with setters works too.
  • It's registered as a bean with @ConfigurationPropertiesScan on the application (or @EnableConfigurationProperties(BoxProperties.class)), and injected like any other: BoxInfoService(BoxProperties box).

Step 4 of 9

Types, lists and nested objects

The Binder converts the text to each field's type:

  • int maxAthletes ← "12".
  • Duration classDuration ← "60m" (also PT45M, 30s, 2h). With @DefaultValue("60m"), if the property is missing.
  • List<String> plans ← a YAML list (or "a,b,c").
  • Address address ← box.address.*: a nested object. With @Valid, its fields are validated too.

There are converters for DataSize (10MB), enums, Map, and so on. The test checks each one.

Step 5 of 9

Relaxed binding

Boot accepts several spellings of the same name:

  • box.max-athletes (kebab-case, the canonical form, recommended in files).
  • box.maxAthletes (camelCase), box.max_athletes.
  • BOX_MAXATHLETES as an environment variable (upper case, the dot becomes _, no dashes).

The test uses box.maxAthletes=25 and an ISO duration (PT45M), and both arrive.

Step 6 of 9

Profile-specific files

With the prod profile active, Boot also loads application-prod.yml, which wins over application.yml:

  • box.max-athletes becomes 20.
  • The rest (name, address…) still comes from application.yml.

The profile is activated with spring.profiles.active=prod (in a file, as -D, as the SPRING_PROFILES_ACTIVE variable or as an argument) or with @ActiveProfiles in tests. In a single YAML you can split documents with --- and spring.config.activate.on-profile: prod.

Step 7 of 9

Who wins? The order in Boot

Boot orders its property sources. Summary, from highest to lowest priority:

  1. Test properties (@TestPropertySource, @SpringBootTest(properties = …)).
  2. Command-line arguments (--box.max-athletes=40).
  3. SPRING_APPLICATION_JSON.
  4. Java system properties (-D).
  5. Environment variables.
  6. Config files: profile-specific outside the jar > profile-specific inside > general outside > general inside.
  7. @PropertySource.
  8. Default properties (SpringApplication.setDefaultProperties).

The test checks it: -D (30) beats both YAML files, and the argument (40) beats everything.

Step 8 of 9

Validating at startup

With @Validated on the properties class and Bean Validation annotations (@NotBlank, @Min, @Max…), the Binder validates while binding. With box.max-athletes=0 the application doesn't start, and the error says which property breaks which rule: box.maxAthletes, "must be greater than or equal to 1".

Step 9 of 9

Recap

  • Files: application.properties/.yml and application-{profile}.yml.
  • Order: tests > command line > -D > environment > files (profile > general, outside > inside) > @PropertySource.
  • @ConfigurationProperties(prefix) + @ConfigurationPropertiesScan: types, lists, nested objects, @DefaultValue.
  • Relaxed binding: max-athletes = maxAthletes = BOX_MAXATHLETES.
  • @Validated: startup fails on invalid values.

Cheatsheet →

Code

ValueBasedSettings.java

/** Before: one @Value per setting, the prefix repeated everywhere, and no validation. */
public class ValueBasedSettings {
    @Value("${box.name}") String name;
    @Value("${box.max-athletes}") int maxAthletes;
    @Value("${box.class-duration}") String classDuration;    // a String: convert it yourself
    @Value("${box.address.city}") String city;
    // …one more line, and one more chance of a typo, for every property
}

BindingTest.java

@Test
void typedBindingFromApplicationYml() {
    assertThat(box.name()).isEqualTo("CrossFit Norte");
    assertThat(box.maxAthletes()).isEqualTo(12);                          // "12" → int
    assertThat(box.classDuration()).isEqualTo(Duration.ofMinutes(60));    // "60m" → Duration
    assertThat(box.plans()).containsExactly("monthly", "ten-pack", "drop-in");
    assertThat(box.address().city()).isEqualTo("Madrid");                  // nested record
}

BoxProperties.java

@ConfigurationProperties(prefix = "box")   // binds box.* onto this record, by name
@Validated                                  // Bean Validation at startup
public record BoxProperties(
    @NotBlank String name,
    @Min(1) @Max(50) int maxAthletes,               // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
    @DefaultValue("60m") Duration classDuration,    // "60m" → Duration.ofMinutes(60)
    List<String> plans,                             // YAML list or "a,b,c"
    @Valid Address address) {                       // nested object: box.address.*

    public record Address(String street, @NotBlank String city) {
    }
}

BoxProperties.java

@ConfigurationProperties(prefix = "box")   // binds box.* onto this record, by name
@Validated                                  // Bean Validation at startup
public record BoxProperties(
    @NotBlank String name,
    @Min(1) @Max(50) int maxAthletes,               // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
    @DefaultValue("60m") Duration classDuration,    // "60m" → Duration.ofMinutes(60)
    List<String> plans,                             // YAML list or "a,b,c"
    @Valid Address address) {                       // nested object: box.address.*

    public record Address(String street, @NotBlank String city) {
    }
}

RelaxedBindingTest.java

@SpringBootTest(properties = {
    "box.maxAthletes=25",              // camelCase works too (relaxed binding)…
    "box.class-duration=PT45M"})       // …and ISO-8601 durations
class RelaxedBindingTest {
    @Autowired
    BoxProperties box;

    @Test
    void manySpellingsOneProperty() {
        assertThat(box.maxAthletes()).isEqualTo(25);
        assertThat(box.classDuration().toMinutes()).isEqualTo(45);
    }
}

ProfileFileTest.java

@SpringBootTest
@ActiveProfiles("prod")                 // loads application-prod.yml on top of application.yml
class ProfileFileTest {
    @Autowired
    BoxProperties box;

    @Test
    void theProfileSpecificFileWins() {
        assertThat(box.maxAthletes()).isEqualTo(20);       // from application-prod.yml
        assertThat(box.name()).isEqualTo("CrossFit Norte"); // still from application.yml
    }
}

PrecedenceAndValidationTest.java

@Test
void commandLineBeatsSystemPropertiesWhichBeatTheFiles() {
    System.setProperty("box.max-athletes", "30");                       // -Dbox.max-athletes=30
    try (var ctx = app().profiles("prod").run()) {
        assertThat(ctx.getBean(BoxProperties.class).maxAthletes()).isEqualTo(30); // beats both yml files
    }
    try (var ctx = app().profiles("prod").run("--box.max-athletes=40")) {
        assertThat(ctx.getBean(BoxProperties.class).maxAthletes()).isEqualTo(40); // command line wins
    }
}

PrecedenceAndValidationTest.java

@Test
void invalidValuesStopTheApplicationAtStartup() {
    assertThatThrownBy(() -> app().run("--box.max-athletes=0").close())  // @Min(1)
        .hasStackTraceContaining("box.maxAthletes")
        .hasStackTraceContaining("must be greater than or equal to 1");
}

BoxProperties.java

@ConfigurationProperties(prefix = "box")   // binds box.* onto this record, by name
@Validated                                  // Bean Validation at startup
public record BoxProperties(
    @NotBlank String name,
    @Min(1) @Max(50) int maxAthletes,               // box.max-athletes, box.maxAthletes, BOX_MAXATHLETES…
    @DefaultValue("60m") Duration classDuration,    // "60m" → Duration.ofMinutes(60)
    List<String> plans,                             // YAML list or "a,b,c"
    @Valid Address address) {                       // nested object: box.address.*

    public record Address(String street, @NotBlank String city) {
    }
}

Quiz

1. The property box.max-athletes is 12 in application.yml, 20 in application-prod.yml, and you start with the prod profile and --box.max-athletes=40. Which value is used?

2. What's the advantage of @ConfigurationProperties over @Value?

3. You have a BoxProperties record annotated with @ConfigurationProperties("box"). What's missing for it to exist as a bean?

4. Which of these does NOT reach the maxAthletes field of @ConfigurationProperties("box") through relaxed binding?

5. BoxProperties carries @Validated and @Min(1) on maxAthletes. You start with box.max-athletes=0. What happens?

6. When is application-prod.yml loaded?

Cheatsheet → · Mock exam →

Run it