Back to Configuration & Profiles
Q5Question 5 of 5

What is @ConfigurationProperties in Spring Boot

Answer: @ConfigurationProperties binds a group of related external configuration properties (from application.yml or application.properties) to a typed Java class, providing type safety, validation, and IDE auto-completion.

Key Concepts
  • @ConfigurationProperties binds a group of related properties from application.yml or application.properties to a typed Java object with getters and setters.
  • The prefix attribute defines the root key in the properties file, and Spring maps nested keys to fields using relaxed binding (kebab-case, camelCase, UPPER_SNAKE all work).
  • Use @Validated with Jakarta Bean Validation annotations (@NotBlank, @Min, @Max) to validate properties at startup, failing fast if values are invalid.
  • @ConfigurationProperties is type-safe: if a property cannot be converted to the field type, the application fails at startup with a clear error message.
  • Compared to @Value, @ConfigurationProperties groups related properties, supports validation, enables IDE auto-completion, and is easier to test.
  • Enable @ConfigurationProperties by adding @EnableConfigurationProperties or @ConfigurationPropertiesScan on a @Configuration class, or by annotating the properties class with @Component.

Definition

@ConfigurationProperties binds a group of related external configuration properties (from application.yml or application.properties) to a typed Java class, providing type safety, validation, and IDE auto-completion.
  • @ConfigurationProperties is a class-level annotation that tells Spring Boot to read properties with a given prefix and bind them to the fields of the annotated class.
  • prefix is the attribute that defines the root key; for example, prefix = "bank.gateway" maps properties like bank.gateway.url, bank.gateway.timeout, bank.gateway.api-key.
  • Relaxed binding is Spring Boot's ability to match property names in different formats: bank.gateway.api-key (kebab), bank.gateway.apiKey (camelCase), BANK_GATEWAY_API_KEY (environment variable) all bind to the same field.
  • @Validated enables Jakarta Bean Validation on the properties class, so @NotBlank, @Min, @Max, @Pattern are checked at startup.
  • @EnableConfigurationProperties is the annotation that registers a @ConfigurationProperties class as a bean in the application context.

Think of National Bank of India configuring a payment gateway integration. Instead of passing 10 separate strings to the PaymentGatewayClient (URL, timeout, API key, retry count, max amount, currency), the bank creates a configuration sheet (the properties class) with labeled fields. An administrator fills in the sheet (application.yml), and Spring binds each labeled field to the matching value. If the admin leaves a required field blank or enters an invalid number, the system rejects the sheet at startup before any customer transaction is processed.

Understanding the Concepts

What is @ConfigurationProperties?

@ConfigurationProperties is a Spring Boot annotation that maps a group of related properties from your configuration file to a Java object. Instead of reading each property individually with @Value, you create a class with fields that match the property names, and Spring Boot populates them automatically.

JAVA
package com.bank.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "bank.gateway")
public class PaymentGatewayProperties {

    private String url;
    private int timeoutMs;
    private int retryCount;
    private String apiKey;

    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
    public int getTimeoutMs() { return timeoutMs; }
    public void setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; }
    public int getRetryCount() { return retryCount; }
    public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
    public String getApiKey() { return apiKey; }
    public void setApiKey(String apiKey) { this.apiKey = apiKey; }

    @Override
    public String toString() {
        return "PaymentGatewayProperties{" +
            "url='" + url + "'" +
            ", timeoutMs=" + timeoutMs +
            ", retryCount=" + retryCount +
            ", apiKey='" + apiKey + "'" +
            "}";
    }
}
YAML
# application.yml
bank:
  gateway:
    url: https://pay.hdfc.com/api/v2
    timeout-ms: 5000
    retry-count: 3
    api-key: sk_live_NBI_2025_secret
TEXT
Spring Boot reads application.yml and binds:
  bank.gateway.url       -> PaymentGatewayProperties.url
  bank.gateway.timeout-ms -> PaymentGatewayProperties.timeoutMs (relaxed binding)
  bank.gateway.retry-count -> PaymentGatewayProperties.retryCount
  bank.gateway.api-key    -> PaymentGatewayProperties.apiKey

How is @ConfigurationProperties different from @Value?

@Value reads one property at a time. @ConfigurationProperties reads a group of properties into a single object.

Feature@Value@ConfigurationProperties
GranularityOne property per fieldAll properties with a prefix
Type safetySpEL can return wrong type at runtimeCompile-time types, fail-fast
ValidationNot built-in@Validated + Jakarta annotations
Relaxed bindingNo (exact key match)Yes (kebab, camel, UPPER_SNAKE)
IDE auto-completionNoYes (with spring-boot-configuration-processor)
Nested objectsManualAutomatic
TestingHard to override in testsEasy with @TestPropertySource
Use caseOne-off values (e.g., a feature flag)Groups of related config
JAVA
package com.bank.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

// @Value approach: each property is separate
@Component
class GatewayConfigWithValue {

    @Value("${bank.gateway.url}")
    private String url;

    @Value("${bank.gateway.timeout-ms}")
    private int timeoutMs;

    @Value("${bank.gateway.retry-count}")
    private int retryCount;

    @Value("${bank.gateway.api-key}")
    private String apiKey;

    @Override
    public String toString() {
        return "GatewayConfigWithValue{url='" + url + "', timeout=" + timeoutMs
            + ", retries=" + retryCount + ", key='" + apiKey + "'}";
    }
}

public class ValueVsConfigProperties {
    public static void main(String[] args) {
        System.out.println("@Value approach:");
        System.out.println("  4 separate @Value annotations");
        System.out.println("  No validation");
        System.out.println("  No relaxed binding");
        System.out.println("  No IDE auto-completion");
        System.out.println();
        System.out.println("@ConfigurationProperties approach:");
        System.out.println("  1 class with prefix = 'bank.gateway'");
        System.out.println("  @Validated + @NotBlank, @Min, @Max");
        System.out.println("  Relaxed binding (kebab, camel, UPPER_SNAKE)");
        System.out.println("  IDE auto-completion with metadata processor");
    }
}
TEXT
Expected output:
@Value approach:
  4 separate @Value annotations
  No validation
  No relaxed binding
  No IDE auto-completion

@ConfigurationProperties approach:
  1 class with prefix = 'bank.gateway'
  @Validated + @NotBlank, @Min, @Max
  Relaxed binding (kebab, camel, UPPER_SNAKE)
  IDE auto-completion with metadata processor

How does relaxed binding work?

Spring Boot matches property names flexibly. All of these bind to the same field:

JAVA
package com.bank.config;

public class RelaxedBindingDemo {
    public static void main(String[] args) {
        System.out.println("Relaxed binding examples for field 'retryCount':");
        System.out.println("  bank.gateway.retry-count   (kebab-case, recommended)");
        System.out.println("  bank.gateway.retryCount    (camelCase)");
        System.out.println("  bank.gateway.retry_count   (underscore)");
        System.out.println("  BANK_GATEWAY_RETRY_COUNT   (environment variable)");
        System.out.println();
        System.out.println("All four bind to:");
        System.out.println("  private int retryCount;");
        System.out.println();
        System.out.println("Best practice:");
        System.out.println("  Use kebab-case in .yml/.properties files");
        System.out.println("  Use camelCase in Java fields");
        System.out.println("  Use UPPER_SNAKE_CASE for environment variables");
    }
}
TEXT
Expected output:
Relaxed binding examples for field 'retryCount':
  bank.gateway.retry-count   (kebab-case, recommended)
  bank.gateway.retryCount    (camelCase)
  bank.gateway.retry_count   (underscore)
  BANK_GATEWAY_RETRY_COUNT   (environment variable)

All four bind to:
  private int retryCount;

Best practice:
  Use kebab-case in .yml/.properties files
  Use camelCase in Java fields
  Use UPPER_SNAKE_CASE for environment variables

How do you validate properties at startup?

Add @Validated to the properties class and use Jakarta Bean Validation annotations on the fields. If validation fails, the application does not start.

JAVA
package com.bank.config;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "bank.gateway")
@Validated
public class ValidatedGatewayProperties {

    @NotBlank(message = "Gateway URL must not be blank")
    private String url;

    @Min(value = 1000, message = "Timeout must be at least 1000ms")
    @Max(value = 30000, message = "Timeout must not exceed 30000ms")
    private int timeoutMs;

    @Min(value = 1, message = "Retry count must be at least 1")
    @Max(value = 5, message = "Retry count must not exceed 5")
    private int retryCount;

    @NotBlank(message = "API key must not be blank")
    private String apiKey;

    // Getters and setters
    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
    public int getTimeoutMs() { return timeoutMs; }
    public void setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; }
    public int getRetryCount() { return retryCount; }
    public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
    public String getApiKey() { return apiKey; }
    public void setApiKey(String apiKey) { this.apiKey = apiKey; }
}
TEXT
With valid configuration (application.yml):
  bank.gateway.url: https://pay.hdfc.com/api
  bank.gateway.timeout-ms: 5000
  bank.gateway.retry-count: 3
  bank.gateway.api-key: sk_live_NBI_2025

  -> Application starts normally.

With invalid configuration:
  bank.gateway.url: (empty)
  bank.gateway.timeout-ms: 500
  bank.gateway.retry-count: 10

  -> Application fails at startup with:
     Binding to target ValidatedGatewayProperties failed:
       Property: bank.gateway.url
       Reason: Gateway URL must not be blank
       Property: bank.gateway.timeout-ms
       Value: 500
       Reason: Timeout must be at least 1000ms

What is a complete banking project using @ConfigurationProperties?

This project binds payment gateway configuration from application.yml to a typed properties class, validates it at startup, and uses it in a service.

Project structure

DIAGRAM
bank-config-props-demo/
├── pom.xml
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/
    │   │       └── bank/
    │   │           ├── BankConfigPropsApp.java
    │   │           ├── config/
    │   │           │   └── PaymentGatewayProperties.java
    │   │           └── service/
    │   │               └── PaymentService.java
    │   └── resources/
    │       └── application.yml
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── config/
                        └── PaymentGatewayPropertiesTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>bank-config-props-demosyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-startersyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-validationsyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

PaymentGatewayProperties.java

JAVA
package com.bank.config;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "bank.gateway")
@Validated
public class PaymentGatewayProperties {

    @NotBlank(message = "Gateway URL is required")
    private String url;

    @Min(value = 1000, message = "Timeout must be at least 1000ms")
    @Max(value = 30000, message = "Timeout must not exceed 30000ms")
    private int timeoutMs = 5000;

    @Min(value = 1, message = "At least 1 retry required")
    @Max(value = 5, message = "Maximum 5 retries allowed")
    private int retryCount = 3;

    @NotBlank(message = "API key is required")
    private String apiKey;

    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
    public int getTimeoutMs() { return timeoutMs; }
    public void setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; }
    public int getRetryCount() { return retryCount; }
    public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
    public String getApiKey() { return apiKey; }
    public void setApiKey(String apiKey) { this.apiKey = apiKey; }

    @Override
    public String toString() {
        return "PaymentGatewayProperties{url='" + url
            + "', timeoutMs=" + timeoutMs
            + ", retryCount=" + retryCount
            + ", apiKey='" + apiKey.substring(0, 8) + "...'}";
    }
}

PaymentService.java

JAVA
package com.bank.service;

import com.bank.config.PaymentGatewayProperties;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PaymentService {

    private final PaymentGatewayProperties gatewayProps;

    public PaymentService(PaymentGatewayProperties gatewayProps) {
        this.gatewayProps = gatewayProps;
    }

    public String processPayment(String accountId, BigDecimal amount) {
        System.out.println("Connecting to: " + gatewayProps.getUrl());
        System.out.println("Timeout: " + gatewayProps.getTimeoutMs() + "ms");
        System.out.println("Max retries: " + gatewayProps.getRetryCount());
        return "Payment of " + amount + " INR for " + accountId + " sent to gateway";
    }
}

application.yml

YAML
bank:
  gateway:
    url: https://pay.hdfc.com/api/v2
    timeout-ms: 5000
    retry-count: 3
    api-key: sk_live_NBI_2025_secret_key_production

BankConfigPropsApp.java

JAVA
package com.bank;

import com.bank.config.PaymentGatewayProperties;
import com.bank.service.PaymentService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.math.BigDecimal;

@SpringBootApplication
@EnableConfigurationProperties(PaymentGatewayProperties.class)
public class BankConfigPropsApp {
    public static void main(String[] args) {
        SpringApplication.run(BankConfigPropsApp.class, args);
    }

    @Bean
    CommandLineRunner demo(PaymentService service, PaymentGatewayProperties props) {
        return args -> {
            System.out.println("Loaded config: " + props);
            System.out.println();
            System.out.println(service.processPayment("SAV2001", new BigDecimal("75000.00")));
        };
    }
}

PaymentGatewayPropertiesTest.java

JAVA
package com.bank.config;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
@TestPropertySource(properties = {
    "bank.gateway.url=https://test-gateway.bank.com",
    "bank.gateway.timeout-ms=2000",
    "bank.gateway.retry-count=1",
    "bank.gateway.api-key=sk_test_12345678"
})
class PaymentGatewayPropertiesTest {

    @Autowired
    private PaymentGatewayProperties props;

    @Test
    void propertiesAreBound() {
        assertEquals("https://test-gateway.bank.com", props.getUrl());
        assertEquals(2000, props.getTimeoutMs());
        assertEquals(1, props.getRetryCount());
        assertEquals("sk_test_12345678", props.getApiKey());
        System.out.println("Test passed: " + props);
    }
}
TEXT
Expected output (application run):
Loaded config: PaymentGatewayProperties{url='https://pay.hdfc.com/api/v2', timeoutMs=5000, retryCount=3, apiKey='sk_live_...'}

Connecting to: https://pay.hdfc.com/api/v2
Timeout: 5000ms
Max retries: 3
Payment of 75000.00 INR for SAV2001 sent to gateway

How to run

BASH
cd bank-config-props-demo
mvn clean package -DskipTests
java -jar target/bank-config-props-demo-1.0.0.jar

# Override with environment variable
BANK_GATEWAY_URL=https://staging.pay.com java -jar target/bank-config-props-demo-1.0.0.jar

# Run tests
mvn test

What about using Java records with @ConfigurationProperties?

Since Spring Boot 3.x, you can use Java records for immutable configuration properties. Spring binds values through the record constructor instead of setters.

JAVA
package com.bank.config;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "bank.gateway")
@Validated
public record PaymentGatewayPropertiesRecord(
    @NotBlank(message = "Gateway URL required") String url,
    @Min(value = 1000) int timeoutMs,
    @Min(value = 1) int retryCount,
    @NotBlank(message = "API key required") String apiKey
) {}
TEXT
Benefits of record-based @ConfigurationProperties:
  1. Immutable: fields are final, no setters needed
  2. Less boilerplate: no getters, setters, toString, equals, hashCode
  3. Thread-safe by default
  4. Constructor binding happens automatically
  5. Works with @Validated for startup validation

What are common mistakes with @ConfigurationProperties?

Wrong: forgetting @EnableConfigurationProperties

JAVA
package com.bank.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "bank.gateway")
public class GatewayPropsNotRegistered {
    private String url;
    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
}
TEXT
Problem: @ConfigurationProperties alone does not register the class as a bean.
Spring throws NoSuchBeanDefinitionException when you try to inject it.
You must either:
  1. Add @EnableConfigurationProperties(GatewayPropsNotRegistered.class) on a @Configuration class
  2. Or add @ConfigurationPropertiesScan on the main class
  3. Or add @Component on the properties class (not recommended)

Correct: register with @EnableConfigurationProperties

JAVA
package com.bank;

import com.bank.config.PaymentGatewayProperties;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(PaymentGatewayProperties.class)
public class CorrectRegistrationApp {
    // PaymentGatewayProperties is now a bean in the context.
}
TEXT
Correct: @EnableConfigurationProperties registers the properties class as a bean.
Spring reads the prefix, binds properties, validates, and makes it available for injection.

Wrong: using @Value for a group of related properties

JAVA
package com.bank.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class GatewayServiceWrong {

    @Value("${bank.gateway.url}") private String url;
    @Value("${bank.gateway.timeout-ms}") private int timeoutMs;
    @Value("${bank.gateway.retry-count}") private int retryCount;
    @Value("${bank.gateway.api-key}") private String apiKey;
    // 4 separate @Value, no validation, no grouping, no IDE support
}
TEXT
Problem: 4 separate @Value annotations for related properties.
No validation at startup. No IDE auto-completion.
If you add a new property, you modify the service class.
Hard to test: must set 4 separate properties.

Correct: use @ConfigurationProperties

JAVA
package com.bank.service;

import com.bank.config.PaymentGatewayProperties;
import org.springframework.stereotype.Service;

@Service
public class GatewayServiceCorrect {

    private final PaymentGatewayProperties props;

    public GatewayServiceCorrect(PaymentGatewayProperties props) {
        this.props = props;
    }
    // One object, validated, typed, IDE-supported.
}
TEXT
Correct: one PaymentGatewayProperties object injected.
All 4 properties are grouped, validated, and type-safe.
Adding a new property means adding a field to the properties class only.

What should a senior or principal engineer know?

  • spring-boot-configuration-processor: add this annotation processor as a dependency to generate META-INF/spring-configuration-metadata.json at compile time. IDEs use this file for auto-completion and documentation of your custom properties.
  • Nested objects: @ConfigurationProperties supports nested classes. For example, bank.gateway.retry.max-attempts and bank.gateway.retry.backoff-ms can map to a nested Retry class inside PaymentGatewayProperties.
  • List and Map binding: properties like bank.gateway.allowed-currencies[0]=INR, bank.gateway.allowed-currencies[1]=USD bind to a List. Properties like bank.gateway.headers.X-Api-Version=2 bind to a Map.
  • Constructor binding: if the class has a single constructor, Spring binds through the constructor (immutable). If it has setters, Spring uses setter binding. Records always use constructor binding.
  • @DefaultValue: use @DefaultValue on constructor parameters to set defaults for constructor-bound properties.
  • Secrets management: do not hardcode API keys in application.yml. Use environment variables, Spring Cloud Config, or a secrets manager. @ConfigurationProperties works with all property sources.
JAVA
package com.bank.core;

public class SeniorConfigPropsKnowledge {
    public static void main(String[] args) {
        System.out.println("Senior/Principal @ConfigurationProperties Checklist:");
        System.out.println("  1. spring-boot-configuration-processor for IDE auto-completion");
        System.out.println("  2. Nested objects for complex configuration groups");
        System.out.println("  3. List and Map binding for dynamic properties");
        System.out.println("  4. Constructor binding for immutability (records, @DefaultValue)");
        System.out.println("  5. @Validated + Jakarta annotations for fail-fast startup");
        System.out.println("  6. Never hardcode secrets; use env vars or secrets manager");
        System.out.println("  7. Relaxed binding: kebab in yml, camelCase in Java, UPPER_SNAKE in env");
    }
}
TEXT
Expected output:
Senior/Principal @ConfigurationProperties Checklist:
  1. spring-boot-configuration-processor for IDE auto-completion
  2. Nested objects for complex configuration groups
  3. List and Map binding for dynamic properties
  4. Constructor binding for immutability (records, @DefaultValue)
  5. @Validated + Jakarta annotations for fail-fast startup
  6. Never hardcode secrets; use env vars or secrets manager
  7. Relaxed binding: kebab in yml, camelCase in Java, UPPER_SNAKE in env

What are common interview follow-up questions?

  • Can @ConfigurationProperties work without setters? (Yes, with constructor binding. Use a single constructor or a Java record. Spring binds through constructor parameters.)
  • How do you override a property in a test? (Use @TestPropertySource(properties = "bank.gateway.url=http://test") on the test class.)
  • What happens if a required property is missing? (With @Validated and @NotBlank, the app fails at startup. Without validation, the field gets its default value, like null for String or 0 for int.)
  • Can you have multiple @ConfigurationProperties classes with different prefixes? (Yes. Each class has its own prefix. Register all of them with @EnableConfigurationProperties or @ConfigurationPropertiesScan.)
  • How do you read properties from a custom file, not application.yml? (Use @PropertySource("classpath:custom.properties") on a @Configuration class. Note: @PropertySource does not work with YAML files by default; you need a custom PropertySourceFactory.)
  • What is the difference between @ConfigurationProperties and @Value? (@ConfigurationProperties is for groups of related properties with validation and relaxed binding. @Value is for individual values with SpEL support.)

Visual Overview

DIAGRAM
 @ConfigurationProperties Binding Flow
 =======================================

 ┌───────────────────────────────────┐
 │ application.yml                    │
 │                                    │
 │ bank:                              │
 │   gateway:                         │
 │     url: https://pay.hdfc.com/api  │
 │     timeout-ms: 5000               │
 │     retry-count: 3                 │
 │     api-key: sk_live_NBI_2025      │
 └───────────────┬───────────────────┘
                 │ Spring reads
                 ▼
 ┌───────────────────────────────────┐
 │ ConfigurationPropertiesBinder      │
 │                                    │
 │ prefix = "bank.gateway"            │
 │                                    │
 │ Relaxed binding:                   │
 │   timeout-ms -> timeoutMs          │
 │   retry-count -> retryCount        │
 │   api-key -> apiKey                │
 └───────────────┬───────────────────┘
                 │ Bind + Validate
                 ▼
 ┌───────────────────────────────────┐
 │ PaymentGatewayProperties           │
 │                                    │
 │ url = "https://pay.hdfc.com/api"   │
 │ timeoutMs = 5000                   │
 │ retryCount = 3                     │
 │ apiKey = "sk_live_NBI_2025"        │
 │                                    │
 │ @Validated -> check @NotBlank,     │
 │   @Min, @Max at startup            │
 └───────────────────────────────────┘
                 │ Register as bean
                 ▼
 ┌───────────────────────────────────┐
 │ PaymentService                     │
 │ (injects PaymentGatewayProperties) │
 └───────────────────────────────────┘

Key Takeaway

@ConfigurationProperties is the Spring Boot way to read groups of related configuration values into a typed Java object. Instead of scattering @Value annotations across your service classes, you create one properties class with a prefix, and Spring binds all matching properties from application.yml.

In our National Bank of India payment gateway project, we bound four properties (url, timeout, retry count, API key) to a single PaymentGatewayProperties class. We added @Validated with @NotBlank and @Min to ensure the application fails at startup if a required property is missing or invalid. The service class injected the properties object through its constructor.

The main advantage over @Value is grouping. With @ConfigurationProperties, related properties live together, can be validated as a unit, and are easy to override in tests with @TestPropertySource. Relaxed binding means you can use kebab-case in YAML, camelCase in Java, and UPPER_SNAKE_CASE in environment variables, and they all map to the same field.

At the senior level, add the spring-boot-configuration-processor dependency for IDE auto-completion, use Java records for immutable properties, support nested objects for complex configuration, and never hardcode secrets in configuration files.

Remember one sentence: @ConfigurationProperties binds a prefixed group of properties from application.yml to a validated, type-safe Java object that you inject where you need it.

---

Share
Use ← → arrow keys to navigate