Configuration
Configuration lets one Orders JAR run on a laptop, in CI, and in production.
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:
@ConfigurationPropertiesScanonOrdersApplicationpicks up records under the prefix. - Validation:
@Validatedis Spring's.@NotBlankisjakarta.validation. Both need the validation starter. - Defaults:
@DefaultValue(org.springframework.boot.context.properties.bind.DefaultValue) is for timeouts, never passwords. @PropertySource: reads.propertiesfiles. YAML needs a customPropertySourceFactory.
Step-by-step explanation
- List currency, tax basis points, and quote timeout. Mark which values are secrets.
- Create
PricingPropsfor prefixorders.pricing, add constraints, and scan it. - Put non-secrets in YAML. Reference secrets as placeholders with no default.
- 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.
@ConfigurationProperties(prefix = "orders.pricing")@Validatedpublic record PricingProps(@NotBlank String currency,@PositiveOrZero int taxBasisPoints,@DefaultValue("2s") Duration quoteTimeout) {@Override public String toString() {return "PricingProps[currency=" + currency+ ", taxBasisPoints=" + taxBasisPoints+ ", quoteTimeout=" + quoteTimeout + "]";}}
orders:pricing:currency: ${ORDERS_CURRENCY}tax-basis-points: 800quote-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.ymloutranks the JAR and should be mode0600, owned by the service user. - Leave
/actuator/envand/actuator/configpropsoff any public port. They print bound values, including keys.
Best practices
- One record per prefix. Inject it instead of a pile of
@Valuestrings. @DefaultValuefor timeouts only. Secrets omit the default.- Pin
server.error.include-stacktrace=neverand the message and binding-error siblings in the packaged file. - Add optional
spring-boot-configuration-processorfor IDE completion, and keep secrets out of metadata defaults.
Common mistakes
- No validation starter.
@NotBlankis ignored and currency stays null. - Logging the record after adding an API key. Generated
toStringships the secret to log aggregation. - A placeholder default for a password. Production keeps the fallback when the variable is forgotten.
@Valueon astaticfield. Injection fills the instance; the static stays at its initializer.- Secrets in
--stripe.api-key. Process listings andkubectl describeshow argv.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionWhich wins, SERVER_PORT or --server.port?+
Answer
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
@NotBlank runs only with spring-boot-starter-validation.3AdvancedQuestionA startup log printed a live API key from a properties record. Why?+
Answer
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.