Centralized Configuration
Spring Cloud Config Server, Git-backed properties, encryption, refresh scope
- Set up a Spring Cloud Config Server backed by a Git repository
- Consume remote config in a client application
- Refresh config at runtime with @RefreshScope and /actuator/refresh
Overview
In a traditional Spring Boot application, configuration is stored in application.properties (or application.yml) files that are bundled with each service. As the number of microservices grows, managing these scattered configuration files becomes increasingly painful and error-prone.
Spring Cloud Config solves this by introducing a centralized configuration management system, where all configuration files for all microservices are stored in a single Git repository and served dynamically through a dedicated Config Server.
Why This Concept Exists The Problems
Problem 1: Rebuild and Redeploy
In a standard Spring Boot setup, configuration lives inside the JAR:
1Order Service JAR2└── application.properties ← config is bundled hereTo change even a single property (e.g., a timeout value or a feature flag), you must:
- Edit
application.properties - Rebuild the JAR
- Redeploy the service
This is a heavyweight operation for what could be a one-line change.
Problem 2: Inconsistent Config Across Services
In a microservices architecture, multiple services often share common configuration — for example, the same database URL:
1Pre-Order Service ──┐2 ├── Both point to the same DB3Post-Order Service ─┘If the DB URL changes, you must update it in every service that uses it. Miss one, and you have inconsistent configuration — a bug that is hard to detect and dangerous in production.
Problem 3: No Runtime Update
application.properties is loaded once — at application startup. If the application is already running and you update the file:
- The running application cannot see the change
- You must stop, rebuild, and restart the service
- This causes downtime
There is no built-in mechanism to pick up configuration changes at runtime in a standard setup.
Problem 4: Time-Consuming Rollback
If a configuration change causes a bug in production:
- You must raise a PR to revert the change
- Get it merged
- Rebuild the service
- Redeploy
If multiple services are affected, this process must be repeated for each one. The rollback process is slow and risky.
The Solution Centralized Configuration with Spring Cloud Config
Three layers:
| Layer | Component | Role |
|---|---|---|
| Layer 1 | Git Repository | Stores all .properties files for all microservices |
| Layer 2 | Config Server | A Spring Boot app that fetches config from Git and serves it |
| Layer 3 | Microservices | Each service contacts the Config Server on startup to fetch its config |
Architecture Diagram
Step 1 Setting Up the Config File Repository
What Is This?
A plain Git repository (no Maven, no Spring Boot — just files) that contains .properties files for all your microservices. This is the single source of truth for all configuration.
Recommended Folder Structure
1config-repo/2├── global/3│ ├── application.properties ← All services, all profiles (default)4│ ├── application-dev.properties ← All services, dev profile5│ ├── application-qa.properties ← All services, QA profile6│ └── application-prod.properties ← All services, prod profile7│8├── order-service/9│ ├── order-service.properties ← Order service, all profiles (default)10│ ├── order-service-dev.properties ← Order service, dev profile11│ ├── order-service-qa.properties ← Order service, QA profile12│ └── order-service-prod.properties ← Order service, prod profile13│14├── invoice-service/15│ ├── invoice-service.properties16│ ├── invoice-service-dev.properties17│ └── ...18│19└── payment-service/20 ├── payment-service.properties21 └── ...Naming Convention Critical Rule
-dev, -qa, -prod) must exactly match the spring.application.name configured in that microservice's application.properties.If Order Service has:
1spring.application.name=order-serviceThen the config repo files must be named:
1order-service.properties2order-service-dev.properties3order-service-qa.properties4order-service-prod.propertiesUnderstanding Precedence The Most Important Concept
The Four Types of Config Files
| File Pattern | Applies To |
|---|---|
application.properties | All services, all profiles (global default) |
application-{profile}.properties | All services, specific profile |
{service-name}.properties | Specific service, all profiles |
{service-name}-{profile}.properties | Specific service, specific profile |
Precedence Order (Highest Lowest)
When Order Service requests its dev profile config, the Config Server searches in this order:
11st → order-service-dev.properties (specific service + specific profile)22nd → application-dev.properties (global + specific profile)33rd → order-service.properties (specific service + all profiles)44th → application.properties (global + all profiles)55th → [local] application-dev.properties (service-local + specific profile)66th → [local] application.properties (service-local default)Precedence Diagram
Concrete Example
Config Repo Contents:
1# global/application.properties2custom.message=Hello from global default3
4# global/application-dev.properties5custom.message=Hello from global dev6
7# order-service/order-service.properties8custom.message=Hello from order default9
10# order-service/order-service-dev.properties11custom.message=Hello from order devRequest: Order Service, profile = dev
Response Array (in precedence order):
1[2 "Hello from order dev", ← order-service-dev.properties (1st)3 "Hello from global dev", ← application-dev.properties (2nd)4 "Hello from order default", ← order-service.properties (3rd)5 "Hello from global default" ← application.properties (4th)6]The first item in the array is the one actually used. The rest are fallbacks.
Step 2 Setting Up the Config Server
What Is the Config Server?
A separate Spring Boot application whose sole responsibility is:
- Connecting to the Git config repository
- Fetching the correct
.propertiesfiles on request - Exposing REST endpoints that microservices can query
Dependency (`pom.xml`)
1<dependency>2 <groupId>org.springframework.cloud</groupId>3 <artifactId>spring-cloud-config-server</artifactId>4</dependency>Select "Config Server" dependency when creating the project in Spring Initializr.
Main Class Enable Config Server
1@SpringBootApplication2@EnableConfigServer // ← This is required3public class ConfigServerApplication {4 public static void main(String[] args) {5 SpringApplication.run(ConfigServerApplication.class, args);6 }7}What does @EnableConfigServer do?
- Signals Spring that this application is a Config Server
- Initializes the necessary beans and repository connectors
- Exposes built-in REST endpoints for clients to query config
- Loads the Git repository on startup (if clone-on-start is true)
@EnableConfigServer, the application is just a regular Spring Boot app. The config-serving beans will not be initialized.Config Server `application.properties`
1server.port=88882
3# ── Git Repository URI ────────────────────────────────────────────────────────4spring.cloud.config.server.git.uri=${GIT_URI}5
6# ── Search Paths (folders to look in) ────────────────────────────────────────7spring.cloud.config.server.git.search-paths=global,order-service,invoice-service8
9# ── Clone behavior ────────────────────────────────────────────────────────────10spring.cloud.config.server.git.clone-on-start=true11
12# ── Default branch to fetch from ─────────────────────────────────────────────13spring.cloud.config.server.git.default-label=main14
15# ── (Optional) Private repo credentials ──────────────────────────────────────16spring.cloud.config.server.git.username=${GIT_USERNAME}17spring.cloud.config.server.git.password=${GIT_TOKEN}Configuration Properties Deep Dive
◆ `spring.cloud.config.server.git.uri`
The URL of the Git repository that holds the config files.
- Public repo: Provide the URL directly; no credentials needed.
- Private repo: Must also provide
usernameandpassword(token).
1# Public repo2spring.cloud.config.server.git.uri=https://github.com/yourorg/config-repo3
4# Private repo5spring.cloud.config.server.git.uri=https://github.com/yourorg/private-config-repo6spring.cloud.config.server.git.username=${GIT_USERNAME}7spring.cloud.config.server.git.password=${GIT_TOKEN}◆ `spring.cloud.config.server.git.search-paths`
Comma-separated list of folders within the repo to search for property files.
1spring.cloud.config.server.git.search-paths=global,order-serviceIf your files are not inside any folder (flat structure), omit this property.
◆ `spring.cloud.config.server.git.clone-on-start`
| Value | Behavior |
|---|---|
true | Download and cache all property files at application startup |
false | Download and cache on first request (lazy loading) |
clone-on-start=true in production. This ensures the Config Server is ready to serve config immediately when it starts, rather than having a cold-start delay on the first request.◆ `spring.cloud.config.server.git.default-label`
The Git branch name to fetch config files from.
1spring.cloud.config.server.git.default-label=main- Default:
main - Use this to point to a feature branch for environment-specific or experimental configs.
- Can also be overridden per-request in the URL (see REST endpoint section).
Private Repository Getting Access Tokens
◆ GitHub
1Profile → Settings → Developer settings → Personal access tokens2→ Fine-grained tokens → Generate new token → Copy token◆ GitLab
1Your Repo → (three dots) → Project Settings → Access Tokens2→ Create token → Copy tokenapplication.properties. Always use environment variables or a secrets manager.◆ Setting Environment Variables in IntelliJ
1Run → Edit Configurations → Environment Variables2
3Add:4GIT_USERNAME=your-username5GIT_TOKEN=your-personal-access-tokenConfig Server Built-In REST Endpoint
Once the Config Server is running, it automatically exposes:
1GET http://localhost:8888/{application}/{profile}/{label}| Parameter | Meaning | Example |
|---|---|---|
application | Service name (spring.application.name) | order-service |
profile | Active profile | dev, qa, prod |
label | Git branch (optional, defaults to main) | main, feature-xyz |
Example Request:
1GET http://localhost:8888/order-service/dev/mainExample Response:
1{2 "name": "order-service",3 "profiles": ["dev"],4 "label": "main",5 "propertySources": [6 {7 "name": "order-service-dev.properties",8 "source": { "custom.message": "Hello from order dev" }9 },10 {11 "name": "application-dev.properties",12 "source": { "custom.message": "Hello from global dev" }13 },14 {15 "name": "order-service.properties",16 "source": { "custom.message": "Hello from order default" }17 },18 {19 "name": "application.properties",20 "source": { "custom.message": "Hello from global default" }21 }22 ]23}The propertySources array is ordered by precedence — the first entry wins.
Step 3 Setting Up Microservices as Config Clients
What Happens on Startup?
When Order Service starts:
- It contacts the Config Server using the URL from
spring.config.import - Sends its
spring.application.nameandspring.profiles.active - Config Server fetches and returns the merged config
- Order Service loads those properties into its Spring
Environment - The properties are available exactly as if they were in a local
application.properties
Dependency (`pom.xml`)
1<dependency>2 <groupId>org.springframework.cloud</groupId>3 <artifactId>spring-cloud-starter-config</artifactId>4</dependency>Client `application.properties`
1# Service name — must match the filename prefix in the config repo2spring.application.name=order-service3
4# Config Server URL5spring.config.import=optional:configserver:http://localhost:88886
7# Active profile8spring.profiles.active=dev9
10# Local fallback values (used if config server is unreachable)11custom.message=Hello from local defaultConfiguration Properties Deep Dive
◆ `spring.application.name`
The name of this service. Must exactly match the filename prefix used in the Git config repository.
1spring.application.name=order-serviceThis tells the Config Server: "Give me the config files prefixed with order-service."
◆ `spring.config.import`
Tells Spring where to import configuration from. For Config Server:
1# With 'optional:' prefix — recommended2spring.config.import=optional:configserver:http://localhost:88883
4# Without 'optional:' — application fails to start if config server is down5spring.config.import=configserver:http://localhost:8888| Prefix | Behavior if Config Server is Down |
|---|---|
optional:configserver: | Application starts normally, uses local properties as fallback |
configserver: | Application fails to start |
optional: in development. In production, you may want to remove it to ensure services don't silently start with stale local config.◆ `spring.profiles.active`
Specifies the active profile. Tells Config Server which profile-specific files to load.
1spring.profiles.active=devCan also be set dynamically at startup:
1java -jar order-service.jar --spring.profiles.active=prodUsing Config in a Controller
1@RestController2@RequestMapping("/order")3public class OrderController {4
5 @Value("${custom.message}") // Injects from wherever config resolves6 private String customMessage;7
8 @GetMapping("/fetch")9 public String fetchConfig() {10 return "Order message: " + customMessage;11 }12}What happens at runtime:
- On startup, Order Service fetches config from Config Server
- Config Server returns
"Hello from order dev"(highest precedence match) @Value("${custom.message}")injects"Hello from order dev"GET /order/fetchreturns"Order message: Hello from order dev"
Complete Flow Diagram
Dynamic Config Update Refresh Scope (Preview)
The Problem:
Your Order Service is running. Someone pushes a new custom.message value to the Git config repo. The Config Server immediately has the new value. But Order Service still uses the old value — because Spring properties are loaded only at startup.
The Solution: Spring Cloud provides @RefreshScope combined with Spring Boot Actuator's /actuator/refresh endpoint.
- Annotate beans that use externalized config with
@RefreshScope - When config changes, hit
POST /actuator/refreshon the microservice - Spring reinitializes all
@RefreshScopebeans with the new config - No restart required
1@RefreshScope // Marks this bean for dynamic refresh2@RestController3@RequestMapping("/order")4public class OrderController {5 @Value("${custom.message}")6 private String customMessage;7
8 @GetMapping("/fetch")9 public String fetchConfig() {10 return customMessage;11 }12}Component Comparison Table
| Component | Type | Role | Key Annotation/Dependency |
|---|---|---|---|
| Git Config Repo | Plain Git repo | Stores all .properties files | None (just files) |
| Config Server | Spring Boot app | Fetches from Git, serves to clients | @EnableConfigServer, spring-cloud-config-server |
| Microservice (Client) | Spring Boot app | Fetches config from Config Server on startup | spring-cloud-starter-config |
Problems Solved Comparison
| Problem | Without Centralized Config | With Spring Cloud Config |
|---|---|---|
| Config change | Rebuild + redeploy required | Update Git repo only |
| Consistency | Must update all services manually | Single source of truth |
| Runtime update | Impossible | Possible with Refresh Scope |
| Rollback | Rebuild + redeploy all affected services | git revert + refresh |
| Profile management | Separate .properties files per service | Centralized with clear naming convention |
Mind Map
Common Mistakes
Mistake 1: Service Name Mismatch
1# In order-service application.properties2spring.application.name=orderService ← camelCase3
4# In Git repo — filename uses hyphenated form5order-service-dev.properties ← won't match!6
7# ✅ Fix: be consistent8spring.application.name=order-service9# and filename: order-service-dev.propertiesMistake 2: Forgetting `@EnableConfigServer`
1@SpringBootApplication2// ❌ Missing @EnableConfigServer — this is just a regular Spring Boot app3public class ConfigServerApplication { ... }4
5// ✅ Correct6@SpringBootApplication7@EnableConfigServer8public class ConfigServerApplication { ... }Mistake 3: Not Using `optional:` in Dev
1# ❌ If Config Server is down, Order Service won't start at all2spring.config.import=configserver:http://localhost:88883
4# ✅ Safer for development5spring.config.import=optional:configserver:http://localhost:8888Mistake 4: Hardcoding Credentials
1# ❌ Never hardcode tokens in properties files2spring.cloud.config.server.git.username=myuser3spring.cloud.config.server.git.password=ghp_actualToken1234
5# ✅ Use environment variables6spring.cloud.config.server.git.username=${GIT_USERNAME}7spring.cloud.config.server.git.password=${GIT_TOKEN}Mistake 5: Missing `search-paths` for Folder-Based Structure
1# ❌ If you organized files into folders and don't specify search-paths,2# Config Server won't find your files3spring.cloud.config.server.git.uri=https://github.com/org/config-repo4
5# ✅ Specify each folder6spring.cloud.config.server.git.search-paths=global,order-service,invoice-serviceBest Practices
- Organize config files into folders by service name for clarity and maintainability.
- Use
optional:configserver:prefix in development to allow the service to start even when the Config Server is unavailable.
- Never hardcode credentials. Use environment variables or a secrets manager (HashiCorp Vault, AWS Secrets Manager) for Git credentials.
- Set
clone-on-start=trueon the Config Server to pre-warm the cache on startup, ensuring instant response to the first client request.
- Use Eureka for Config Server discovery rather than hardcoding the Config Server URL in every microservice's properties. This avoids a single point of configuration failure.
- Use meaningful
default-labelto allow blue/green config deployments — push new config to a branch and only switch when ready.
- Keep local
application.propertiesminimal — just enough for the service to start when the Config Server is unavailable (optional:mode). All real config should live in the Git repo.
- Version your config changes using Git branches and tags for traceability and easy rollback (
git revertis all you need).
Interview Questions
Q1: What problems does Spring Cloud Config solve?
Answer: Four main problems:
- Rebuild/redeploy for every config change
- Inconsistent config across multiple services sharing common properties
- No runtime update —
application.propertiesis loaded only at startup - Slow rollback — any config mistake requires rebuild and redeploy of all affected services
Q2: What are the three layers of Spring Cloud Config?
Answer:
- Layer 1 — Git Config Repository: A plain Git repo containing
.propertiesfiles for all services. - Layer 2 — Config Server: A Spring Boot app annotated with
@EnableConfigServer. Fetches config from Git and exposes a REST API. - Layer 3 — Microservices (Clients): Each service has the
spring-cloud-starter-configdependency and contacts the Config Server on startup.
Q3: Explain the configuration precedence in Spring Cloud Config.
Answer: When a service requests config for a specific profile, the lookup order (highest to lowest precedence) is:
{service-name}-{profile}.properties— most specificapplication-{profile}.properties— global, same profile{service-name}.properties— same service, all profilesapplication.properties— global default- Local
application-{profile}.properties - Local
application.properties— least specific
Q4: What does `optional:configserver:` mean in `spring.config.import`?
Answer: The optional: prefix tells Spring Boot that if the Config Server is unreachable, the application should still start normally using local application.properties as a fallback. Without optional:, the application will refuse to start if it cannot reach the Config Server.
Q5: What is `clone-on-start` and why should it be `true`?
Answer: When clone-on-start=true, the Config Server downloads and caches all config files from Git at application startup. If false, it downloads on the first client request (lazy). Setting it to true is preferred because it ensures the Config Server is immediately ready to serve requests and exposes Git connectivity issues at startup rather than at runtime.
Q6: How would you handle private Git repositories in Spring Cloud Config?
Answer: Provide Git credentials via spring.cloud.config.server.git.username and .password. For GitHub, create a Personal Access Token (Profile → Settings → Developer Settings → Personal Access Tokens). For GitLab, create a Project Access Token (Project Settings → Access Tokens). Always read credentials from environment variables, never hardcode them in application.properties.
Q7: How does a microservice know which config to fetch from the Config Server?
Answer: Two properties determine this:
spring.application.name— tells the Config Server which service-specific files to look forspring.profiles.active— tells the Config Server which profile-specific files to include
The Config Server uses these to construct the correct file lookup and returns a precedence-ordered array of property sources.
Q8: What is `default-label` in the Config Server configuration?
Answer: It specifies the Git branch from which config files are fetched. Default is main. You can override it for feature-specific or environment-specific configs. Can also be overridden per-request in the Config Server REST endpoint URL: /{application}/{profile}/{label}.
Practice Questions
Easy
- What are the four problems that centralized configuration solves?
- What annotation is required on the Config Server's main class?
- What is the naming convention for a config file specific to
order-servicein thedevprofile? - What dependency does a microservice need to act as a config client?
Medium
- Given this folder structure in the Git config repo, list the full precedence order when
invoice-servicerequests theprodprofile. - What is the difference between
configserver:andoptional:configserver:inspring.config.import? When would you use each? - Your company uses a private GitHub repo for config files. Walk through the exact steps to configure the Config Server to access it securely.
- If
clone-on-start=falseand the Config Server restarts, what happens to the cache? When is the cache repopulated?
Hard
- A developer pushes a new property value to the Git config repo. The Config Server is running. Order Service is also running. Will Order Service pick up the new value automatically? Why or why not? What mechanism would allow it to do so without restarting?
- Your team has 20 microservices. How would you structure the Git config repo to minimize duplication while maintaining service-specific overrides? Describe the folder structure and naming convention.
- The Config Server itself has configuration (its
application.properties). How do you prevent the Config Server from becoming a single point of failure in your architecture? - Compare the tradeoffs of using
optional:configserver:vs requiring the Config Server to be available before any microservice starts.
Summary
- Spring Cloud Config centralizes configuration management for all microservices.
- Three components: Git repo (config files) → Config Server → Microservices (clients).
- The Git repo holds plain
.propertiesfiles organized by service and profile. - Naming convention:
{service-name}-{profile}.propertiesfor service-specific profile config. - Precedence (high → low): service+profile → global+profile → service+default → global+default → local+profile → local+default.
- Config Server is a Spring Boot app with
@EnableConfigServerandspring-cloud-config-serverdependency. - Config Server exposes:
GET /{application}/{profile}/{label} - Microservices use
spring-cloud-starter-configandspring.config.import=optional:configserver:URL. spring.application.namemust match the filename prefix in the Git repo.optional:prefix prevents startup failure when Config Server is unreachable.- For private repos: provide
username+ access token via environment variables. clone-on-start=truepre-warms the Config Server cache at startup.default-labelspecifies the Git branch to fetch config from (default:main).- Runtime updates require
@RefreshScope+ Spring Boot Actuator (covered in the next lecture).
Mastery check
How well can you recall this?
Finished this lesson?