Skip to main content

Configuration Management in Spring Boot

Configuration Management in Spring Boot: Complete Deep Dive

Configuration Management is an absolutely essential topic for backend developers. Almost every real-world application requires externalized configuration to manage things like Database credentials, Server Ports, Security keys, Kafka brokers, Redis endpoints, and Cloud Services.


1. What is Configuration Management?

Standard Definition

Configuration Management is the architectural process of externalizing application settings away from the compiled source code, allowing environments to be altered purely via configuration files.

Instead of hardcoding a database URL in Java:

String url = "jdbc:mysql://localhost:3306/company";

We externalize it:

spring.datasource.url=jdbc:mysql://localhost:3306/company

Core Benefits:

  • No recompilation needed to change environments.
  • Environment-Specific Configuration (Dev, QA, Prod).
  • Easier deployments and Docker/Kubernetes integration.
  • Security (keeping passwords out of source control).

2. Where Does Spring Boot Store Configuration?

The main property files are typically located in the src/main/resources directory.

application.properties (Traditional)

server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root

application.yml (Modern YAML)

server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root

Why is YAML so popular?

YAML eliminates massive amounts of repetition through nested tree structures. For example, HikariCP properties look much cleaner:

# Properties approach: spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.connection-timeout=30000 # YAML approach: spring: datasource: hikari: maximum-pool-size: 20 minimum-idle: 5 connection-timeout: 30000

3. The Internal Loading Engine: The Environment Object

This is a major interview topic. When Spring Boot starts up, it creates an interface called the Environment. This object acts as the central repository for all configuration data.

Application Start | SpringApplication.run() | Create Environment Object | Load application.properties/yml | Convert Into Property Sources | Store Inside Environment | Available For Injection

If you need to fetch a raw property programmatically, you can autowire the Environment directly:

@Autowired private Environment environment; String port = environment.getProperty("server.port");

The PropertySource Hierarchy

Spring Boot doesn't just read your application.yml. It reads from multiple locations and combines them into PropertySource objects. If there is a conflict, the higher priority overrides the lower.

  1. Command Line Arguments (Highest Priority)
  2. OS Environment Variables
  3. application.properties / application.yml
  4. Default Values (Lowest Priority)

Example: If your file says server.port=8080 but you start the app with java -jar app.jar --server.port=9090, the app will run on 9090.


4. The @Value Annotation

@Value is used to inject a single property value directly into a bean field.

@Value("${server.port}") private String port;

Internal Working Flow

During the bean lifecycle, the AutowiredAnnotationBeanPostProcessor scans fields for annotations. When it finds @Value, it queries the PropertyResolver, which fetches the string from the Environment and injects it.

@Value("${server.port}") | Property Resolver | Environment | application.properties -> "8080" | Inject Into Field

Default Values and SpEL

You can provide fallback default values using a colon (:). If the property is missing, the default is used instead of crashing the app.

@Value("${server.port:9090}") private String port;

@Value also supports the Spring Expression Language (SpEL):

@Value("#{2+5}") // Evaluates to 7 private int value;

5. The @ConfigurationProperties Paradigm

Imagine mapping an employee configuration using @Value:

@Value("${employee.name}") private String name; @Value("${employee.age}") private int age; @Value("${employee.city}") private String city;

This creates massive amounts of boilerplate. This is exactly where @ConfigurationProperties shines.

Standard Definition

@ConfigurationProperties binds a group of related properties into a single, strongly-typed Java object.

@ConfigurationProperties(prefix = "employee") @Component public class EmployeeProperties { private String name; private int age; private String city; // Getters and Setters required! }

Internal Backend Flow

Spring Boot relies on a component called the ConfigurationPropertiesBindingPostProcessor and the Binder API to map these values automatically.

@ConfigurationProperties | ConfigurationPropertiesBindingPostProcessor | Binder API | Environment Property Sources | Java Object Injection

Nested Object Binding

This is incredibly common in Microservices architectures.

# application.yml database: mysql: url: localhost username: root
@ConfigurationProperties(prefix="database") @Component public class DatabaseProperties { private Mysql mysql; public static class Mysql { private String url; private String username; } }

JSR-303 Validation Support

By adding @Validated, Spring will refuse to start if bad configurations are detected. This is a massive lifesaver in production environments.

@ConfigurationProperties(prefix="employee") @Validated public class EmployeeProperties { @NotBlank private String name; @Min(18) private int age; }

6. @Value vs @ConfigurationProperties (The Ultimate Interview Comparison)

Feature @Value @ConfigurationProperties
Core Purpose Single Property Injection Group Properties Binding
Type Safety Limited Strongly Typed
Nested Properties Very Difficult / Clunky Excellent (Native Support)
Validation (@Validated) No Yes
SpEL Support (#{...}) Yes No
Maintainability Low (Scattered logic) High (Centralized objects)
Microservices Preference Not Preferred Highly Preferred

When to use which?

  • Use @Value when: You only need a tiny, isolated configuration (e.g., just injecting server.port into a logging service).
  • Use @ConfigurationProperties when: You are configuring complex domains like Databases, Kafka Brokers, Redis Caches, or any custom feature flag groups in a Microservices architecture.

7. Complete Master Blueprint Diagram

SpringApplication.run() | Create Environment | Load application.properties / yml | Create PropertySources | Store In Environment | +----------------------+ | | @Value @ConfigurationProperties | | PropertyResolver Binder | | Inject Value Bind Entire Object | | +-----------+----------+ | Bean Ready

Top Interview Q&A Summary

Q: Explain Bean Configuration Management.
A: Spring Boot externalizes application settings into configuration files (like YAML) and maps them into the core Environment object. From there, they are injected into Beans using property binding mechanisms.

Q: How does @Value work internally?
A: The PropertyResolver reads values from the Environment, resolves placeholder strings like ${server.port}, evaluates any SpEL expressions, and injects the result into the field during bean initialization.

Q: How does @ConfigurationProperties work internally?
A: The Spring Boot Binder API takes a group of related properties from the Environment and structurally maps them onto a strongly typed Java object, supporting nested hierarchies and JSR-303 validation.

Q: What internal classes handle this?
A: If the interviewer digs deep, mention: Environment, PropertySource, PropertySourcesPropertyResolver, ConfigurationPropertiesBindingPostProcessor, and Binder.

Comments

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Strings in C

C Programming: Working with Strings Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters. Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator ( \0 ). 1. Essential String Functions Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text. strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the \0 terminator. It does not count the terminator itself. strcpy(): You ...