Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 10

    Configuration

    Configuration lets one Orders JAR run on a laptop, in CI, and in production.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Configuration lets one Orders JAR run on a laptop, in CI, and in production. Boot externalizes port, currency, timeouts, and secrets. The binary stays immutable.

    Highest precedence first, for the sources you will actually fight: command-line arguments, then SPRING_APPLICATION_JSON, then -D system properties, then environment variables, then profile files, then packaged application.yml. @TestPropertySource and DevTools global settings sit higher still. A file beside the JAR outranks the copy inside it.

    Bind a group of keys with @ConfigurationProperties on a Java 21 record. Boot 3 uses the canonical constructor, so you do not add @ConstructorBinding. @Validated plus Jakarta constraints fail startup on a blank currency — but only if spring-boot-starter-validation is present. @Value remains fine for a single flag.

    Relaxed binding is one property in three spellings: orders.pricing.tax-basis-points, Java taxBasisPoints, and ORDERS_PRICING_TAX_BASIS_POINTS.

    Purpose of this lesson

    Bind Orders pricing to a validated record, override it per environment without a rebuild, and fail startup when a required key is missing.

    Understanding the topic

    A prefix should be a typed object with a boot-time contract.

    • Scan: @ConfigurationPropertiesScan on OrdersApplication picks up records under the prefix.
    • Validation: @Validated is Spring's. @NotBlank is jakarta.validation. Both need the validation starter.
    • Defaults: @DefaultValue (org.springframework.boot.context.properties.bind.DefaultValue) is for timeouts, never passwords.
    • @PropertySource: reads .properties files. YAML needs a custom PropertySourceFactory.

    Step-by-step explanation

    1. List currency, tax basis points, and quote timeout. Mark which values are secrets.
    2. Create PricingProps for prefix orders.pricing, add constraints, and scan it.
    3. Put non-secrets in YAML. Reference secrets as placeholders with no default.
    4. Inject the record into OrderService. Boot once with the currency variable missing and confirm the process exits during binding.

    Informative example

    800 basis points is 8.00%. Tax stays an integer. Override toString if a secret ever joins the record — the generated method prints every component. ORDERS_CURRENCY has no fallback, so a missing variable aborts startup.

    java
    @ConfigurationProperties(prefix = "orders.pricing")
    @Validated
    public record PricingProps(
    @NotBlank String currency,
    @PositiveOrZero int taxBasisPoints,
    @DefaultValue("2s") Duration quoteTimeout
    ) {
    @Override public String toString() {
    return "PricingProps[currency=" + currency
    + ", taxBasisPoints=" + taxBasisPoints
    + ", quoteTimeout=" + quoteTimeout + "]";
    }
    }
    bash
    orders:
    pricing:
    currency: ${ORDERS_CURRENCY}
    tax-basis-points: 800
    quote-timeout: 2s

    Real-world use

    TechLearningPro Orders publishes one image. Dev uses USD and 800 basis points; a region sets ORDERS_CURRENCY and a different tax value in the environment. The Stripe key is a separate variable on the deployment and never enters an image layer — Docker keeps a deleted file in earlier layers. A bad deploy crashes before the load balancer sends traffic.

    Security implications

    Bound configuration is a secret store whether you planned that or not.

    • Commit no API keys or database passwords. Currency may have a dev default; a Stripe key may not.
    • An external ./config/application.yml outranks the JAR and should be mode 0600, owned by the service user.
    • Leave /actuator/env and /actuator/configprops off any public port. They print bound values, including keys.

    Best practices

    • One record per prefix. Inject it instead of a pile of @Value strings.
    • @DefaultValue for timeouts only. Secrets omit the default.
    • Pin server.error.include-stacktrace=never and the message and binding-error siblings in the packaged file.
    • Add optional spring-boot-configuration-processor for IDE completion, and keep secrets out of metadata defaults.

    Common mistakes

    • No validation starter. @NotBlank is ignored and currency stays null.
    • Logging the record after adding an API key. Generated toString ships the secret to log aggregation.
    • A placeholder default for a password. Production keeps the fallback when the variable is forgotten.
    • @Value on a static field. Injection fills the instance; the static stays at its initializer.
    • Secrets in --stripe.api-key. Process listings and kubectl describe show argv.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionWhich wins, SERVER_PORT or --server.port?+

    Answer

    The command-line argument. Environment variables beat packaged application.yml, and a file next to the JAR beats the copy inside it. Test property sources sit above the whole list.
    2BeginnerQuestionWhy a record of @ConfigurationProperties instead of several @Value parameters?+

    Answer

    The record groups the prefix, validates as one object, and is a normal constructor argument. Boot 3 binds it through the canonical constructor. @NotBlank runs only with spring-boot-starter-validation.
    3AdvancedQuestionA startup log printed a live API key from a properties record. Why?+

    Answer

    Records generate toString from every component. Override it, keep credentials in a type you never log, prefer env or a file mount over argv, and do not expose /actuator/env.

    Hands-on exercise

    Lab. Bind PricingProps and point currency at the ORDERS_CURRENCY placeholder with no default. Start without the variable and capture the failure. Export ORDERS_CURRENCY=USD, restart, and confirm the order JSON contains USD.

    Summary

    PricingProps absorbs currency, tax basis points, and timeouts from the environment, so Orders stays one JAR. Constructor binding plus validation aborts a bad deploy, and relaxed binding lets the platform speak ORDERS_PRICING_TAX_BASIS_POINTS.

    Ready to mark this lesson complete?Track your journey across the entire course.