Skip to lesson

@Value and @ConfigurationProperties

ShopLite code needs a low-stock threshold, a page size and a support email. Reading each one with its own string key spreads typos and unchecked values over many classes.

@Value: one setting, with a default

@Value injects one setting into one constructor parameter, written @Value("${key:default}"). The ${...} part is a placeholder that Spring replaces with the value; the text after the colon is the default.

@Value("${shoplite.low-stock-threshold:5}") puts the setting shoplite.low-stock-threshold into a constructor parameter. The 5 after the colon is the default, used when no source sets the key.

Example 1 · StockAlert.java with @Value, and a runner

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

StockAlert.javaJava
// src/main/java/com/shoplite/lab/StockAlert.javapackage com.shoplite.lab;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
@Componentpublic class StockAlert {
    private final int threshold;    private final String supportEmail;
    public StockAlert(@Value("${shoplite.low-stock-threshold:5}") int threshold,                      @Value("${shoplite.support-email}") String supportEmail) {        this.threshold = threshold;        this.supportEmail = supportEmail;    }
    public String check(String product, int stock) {        if (stock <= threshold) {            return "LOW: " + product + " has " + stock + " left (alert at " + threshold + "), mail " + supportEmail;        }        return "OK:  " + product + " has " + stock + " left";    }}
// src/main/java/com/shoplite/lab/StockReport.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class StockReport implements CommandLineRunner {
    private final StockAlert alert;
    public StockReport(StockAlert alert) {        this.alert = alert;    }
    @Override    public void run(String... args) {        System.out.println(alert.check("iPhone 15 128GB", 8));        System.out.println(alert.check("HP Victus 15 Gaming", 5));        System.out.println(alert.check("boAt Airdopes 141", 120));    }}
# src/main/resources/application.propertiesspring.main.banner-mode=offlogging.level.root=warn
shoplite.support-email=stock@shoplite.example
Output
OK:  iPhone 15 128GB has 8 left
LOW: HP Victus 15 Gaming has 5 left (alert at 5), mail stock@shoplite.example
OK:  boAt Airdopes 141 has 120 left

What this code does

  • The file does not set shoplite.low-stock-threshold, so the default 5 is used: 5 left is LOW, 8 left is OK. shoplite.support-email has no default, but the file sets it.
  • Run it with --shoplite.low-stock-threshold=10 and the iPhone line becomes LOW: iPhone 15 128GB has 8 left (alert at 10), ... without any code change.
  • Both values arrive through the constructor, so threshold can be final and is set before check is ever called.

Example 2 · No default and no value: Could not resolve placeholder

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

Properties
# src/main/resources/application.properties (shoplite.support-email removed)spring.main.banner-mode=offlogging.level.root=warn
Sample output
2026-10-16T11:27:46.240+05:30 ERROR 14440 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockAlert' defined in file [...\StockAlert.class]: Unexpected exception during bean creation
Caused by: org.springframework.util.PlaceholderResolutionException: Could not resolve placeholder 'shoplite.support-email' in value "${shoplite.support-email}"
	... 15 common frames omitted

What this code does

  • Same StockAlert as Example 1, but the file no longer sets shoplite.support-email. That placeholder has no :default, so Spring cannot create the stockAlert bean and the app stops.
  • Read the last Caused by line: it names the exact key. Add it to a file, an environment variable or a -- argument, or give the placeholder a default.

Spring also converts the text to the parameter's type, so an int parameter gets the number 5. If the text cannot be converted (five), start-up stops with Failed to convert value of type 'java.lang.String' to required type 'int'.

Without a default, a missing key stops start-up with Could not resolve placeholder, as Example 2 shows. That is good for values the app cannot run without. Put @Value on constructor parameters, never on fields, so the value is there before your constructor uses it.

@ConfigurationProperties: a typed ShopLiteProperties record

@ConfigurationProperties binds all settings under one prefix to the components of a typed class or record, using Java types such as int, Duration, BigDecimal and List.

@ConfigurationProperties("shoplite") on a record fills each component from the setting with that prefix: lowStockThreshold from shoplite.low-stock-threshold. Relaxed binding does the name matching.

Example 3 · ShopLiteProperties.java bound with @ConfigurationProperties

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

ShopLiteProperties.javaJava
// src/main/java/com/shoplite/lab/ShopLiteProperties.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.time.Duration;import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties("shoplite")public record ShopLiteProperties(        @DefaultValue("5") int lowStockThreshold,        @DefaultValue("20") int defaultPageSize,        @DefaultValue("100") int maxPageSize,        String supportEmail,        @DefaultValue("30m") Duration cartExpiry,        Delivery delivery) {
    public record Delivery(BigDecimal freeAbove, BigDecimal charge, List<String> cities) {    }}
// src/main/java/com/shoplite/lab/ConfigLabApplication.javapackage com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication@ConfigurationPropertiesScanpublic class ConfigLabApplication {
    public static void main(String[] args) {        SpringApplication.run(ConfigLabApplication.class, args);    }}
// src/main/java/com/shoplite/lab/SettingsReport.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class SettingsReport implements CommandLineRunner {
    private final ShopLiteProperties props;
    public SettingsReport(ShopLiteProperties props) {        this.props = props;    }
    @Override    public void run(String... args) {        System.out.println(props);        System.out.println("Page size " + props.defaultPageSize() + ", at most " + props.maxPageSize());        System.out.println("Cart expires after " + props.cartExpiry().toMinutes() + " minutes");
        ShopLiteProperties.Delivery delivery = props.delivery();        BigDecimal cart = new BigDecimal("450.00");        BigDecimal charge = cart.compareTo(delivery.freeAbove()) >= 0 ? BigDecimal.ZERO : delivery.charge();        System.out.println("Delivery on a Rs " + cart + " cart: Rs " + charge);        System.out.println("We deliver to " + delivery.cities().size() + " cities: " + delivery.cities());    }}
# src/main/resources/application.propertiesspring.main.banner-mode=offlogging.level.root=warn
shoplite.low-stock-threshold=10shoplite.support-email=help@shoplite.exampleshoplite.cart-expiry=45mshoplite.delivery.free-above=499.00shoplite.delivery.charge=40.00shoplite.delivery.cities=Pune,Chennai,Kochi
Output
ShopLiteProperties[lowStockThreshold=10, defaultPageSize=20, maxPageSize=100, supportEmail=help@shoplite.example, cartExpiry=PT45M, delivery=Delivery[freeAbove=499.00, charge=40.00, cities=[Pune, Chennai, Kochi]]]
Page size 20, at most 100
Cart expires after 45 minutes
Delivery on a Rs 450.00 cart: Rs 40.00
We deliver to 3 cities: [Pune, Chennai, Kochi]

What this code does

  • One record holds every shoplite.* setting. defaultPageSize and maxPageSize are not in the file, so their @DefaultValues 20 and 100 are used; lowStockThreshold is 10 from the file.
  • cart-expiry=45m became a Duration (PT45M, 45 minutes), free-above a BigDecimal, and cities a List of three, with no parsing code.
  • @ConfigurationPropertiesScan on the main class turns the record into a bean, so SettingsReport receives it in its constructor like any other bean.

The record gets real Java types. Duration reads 45m or 2h, BigDecimal keeps money exact, a List<String> reads Pune,Chennai,Kochi, and a nested record (Delivery) reads every key under shoplite.delivery. @DefaultValue("20") on a component gives it a default.

Any bean that needs settings asks for ShopLiteProperties in its constructor and calls props.maxPageSize(). No key strings are spread across the code.

Add the dependency spring-boot-configuration-processor (Spring Initializr: "Spring Configuration Processor") and IntelliJ IDEA will auto-complete your own shoplite.* keys in application.properties.

Registering it with @ConfigurationPropertiesScan

@ConfigurationPropertiesScan on the main class tells Boot to find every @ConfigurationProperties class in that package and below, bind it and register it as a bean.

A @ConfigurationProperties record is not a bean on its own: Boot must be told where to find it. Example 3 uses @ConfigurationPropertiesScan; the snippet below names the class by hand instead.

PropertiesConfig.javaJava
import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Configuration;
// The other way: list each properties class by name@Configuration@EnableConfigurationProperties(ShopLiteProperties.class)public class PropertiesConfig {}

Example 4 · Forgetting @ConfigurationPropertiesScan

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

ConfigLabApplication.javaJava
// src/main/java/com/shoplite/lab/ConfigLabApplication.javapackage com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class ConfigLabApplication {
    public static void main(String[] args) {        SpringApplication.run(ConfigLabApplication.class, args);    }}
Sample output
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.shoplite.lab.SettingsReport required a bean of type 'com.shoplite.lab.ShopLiteProperties' that could not be found.


Action:

Consider defining a bean of type 'com.shoplite.lab.ShopLiteProperties' in your configuration.

What this code does

  • The record and the runner are the same as in Example 3; only the annotation on the main class is gone.
  • Spring never registered ShopLiteProperties as a bean, so SettingsReport cannot be created. Add @ConfigurationPropertiesScan back (or @EnableConfigurationProperties).

Forget both ways and start-up stops with required a bean of type 'com.shoplite.lab.ShopLiteProperties' that could not be found, as Example 4 shows. The record exists, but nothing told Spring to create it.

Do not put @Component on a record: Spring would try to call its constructor with beans instead of settings.

Validating settings with @Validated

Fail fast means stopping at start-up when configuration is bad, instead of failing later when a customer meets the problem. @Validated on a properties record makes Boot check its values at start-up.

@Validated on a properties record makes Boot run Bean Validation on the bound values: the same @Min, @Max, @NotBlank and @Email you use for request bodies. It needs spring-boot-starter-validation.

Example 5 · ShopLiteProperties.java with @Validated, and two bad values

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

ShopLiteProperties.javaJava
// src/main/java/com/shoplite/lab/ShopLiteProperties.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.time.Duration;import java.util.List;
import jakarta.validation.Valid;import jakarta.validation.constraints.Email;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotEmpty;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.PositiveOrZero;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.bind.DefaultValue;import org.springframework.validation.annotation.Validated;
@Validated@ConfigurationProperties("shoplite")public record ShopLiteProperties(        @DefaultValue("5") @Min(0) int lowStockThreshold,        @DefaultValue("20") @Min(1) @Max(100) int defaultPageSize,        @DefaultValue("100") @Min(1) @Max(100) int maxPageSize,        @NotBlank @Email String supportEmail,        @DefaultValue("30m") @NotNull Duration cartExpiry,        @Valid @NotNull Delivery delivery) {
    public record Delivery(@NotNull @PositiveOrZero BigDecimal freeAbove,                           @NotNull @PositiveOrZero BigDecimal charge,                           @NotEmpty List<String> cities) {    }}
# src/main/resources/application.propertiesspring.main.banner-mode=offlogging.level.root=warn
shoplite.max-page-size=500shoplite.support-email=help-at-shopliteshoplite.delivery.free-above=499.00shoplite.delivery.charge=40.00shoplite.delivery.cities=Pune,Chennai,Kochi
Sample output
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.shoplite.lab.ShopLiteProperties failed:

    Property: shoplite.supportEmail
    Value: "help-at-shoplite"
    Origin: class path resource [application.properties] - 5:24
    Reason: must be a well-formed email address

    Property: shoplite.maxPageSize
    Value: "500"
    Origin: class path resource [application.properties] - 4:24
    Reason: must be less than or equal to 100


Action:

Update your application's configuration

What this code does

  • Both broken settings are reported at once, each with its value, the file line it came from and the reason. The order of the entries can differ between runs.
  • @Valid on delivery makes the nested record's @NotNull and @NotEmpty checks run too.
  • With valid values (max-page-size=100, a real email) the app starts and prints the same report as Example 3.

A bad value now stops the app with an APPLICATION FAILED TO START report. The report names every broken property, the bad value, the file and line it came from (Origin: class path resource [application.properties] - 4:24) and the reason.

Without validation, max-page-size=500 would start fine and only hurt later, when a client asks for 500 rows. A nested record needs @Valid on its component, or its own constraints are never checked.

Why typed properties beat scattered @Value strings

Each @Value repeats a key as a string. A typo such as free-abov is not a compile error: with a default, the code quietly uses the default forever, as Example 6 shows.

Example 6 · DeliveryRules.java: a typo in a @Value key

Runs in: the config-lab practice project with spring-boot-starter-validation (Spring Boot 4.1)

DeliveryRules.javaJava
// src/main/java/com/shoplite/lab/DeliveryRules.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
@Componentpublic class DeliveryRules {
    private final BigDecimal freeAbove;    private final BigDecimal charge;
    public DeliveryRules(@Value("${shoplite.delivery.free-abov:999}") BigDecimal freeAbove,   // typo: "abov"                         @Value("${shoplite.delivery.charge:40}") BigDecimal charge) {        this.freeAbove = freeAbove;        this.charge = charge;    }
    public BigDecimal chargeFor(BigDecimal cartTotal) {        return cartTotal.compareTo(freeAbove) >= 0 ? BigDecimal.ZERO : charge;    }}
// src/main/java/com/shoplite/lab/CartRunner.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class CartRunner implements CommandLineRunner {
    private final DeliveryRules rules;
    public CartRunner(DeliveryRules rules) {        this.rules = rules;    }
    @Override    public void run(String... args) {        BigDecimal cart = new BigDecimal("650.00");        System.out.println("Cart Rs " + cart + ", delivery Rs " + rules.chargeFor(cart));    }}
# src/main/resources/application.propertiesspring.main.banner-mode=offlogging.level.root=warn
shoplite.delivery.free-above=499.00shoplite.delivery.charge=40.00
Output
Cart Rs 650.00, delivery Rs 40.00

What this code does

  • The file sets free delivery above Rs 499, so a Rs 650 cart should ship free. The key in the code says free-abov, which nobody sets, so the default 999 is used and the customer pays Rs 40.
  • Nothing fails and nothing is logged; only a careful tester notices. With ShopLiteProperties, the name comes from the record component freeAbove, so this typo cannot happen in code.

With twenty settings spread over ten classes, nobody can see the full list either. A properties record fixes both problems: every shoplite.* setting is in one file, the names come from record components the compiler checks, and validation runs once at start-up. A unit test can build the record with new ShopLiteProperties(...) and pass it in, without Spring.

Keep @Value for one-off values in a single class. Use a properties record for any group of related settings, which is how ShopLite works from now on.

Find the bug

Find the configuration bug

Each snippet misreads or misses a setting. Tap the wrong line, then check the fix.

The file sets shoplite.free-above=499, but customers still pay for delivery on Rs 650.

Round 1 of 4

Next step

Check your understanding

11 quick questions