Skip to main content

Chapter 3: Centralized Configuration with Spring Cloud Config

🎯 Chapter Objectives​

  • Understand the need for centralized configuration
  • Set up a Spring Cloud Config Server
  • Connect services as Config Clients
  • Use Git as a configuration backend
  • Implement hot refresh of configuration
  • Manage encryption of secrets

1. Why Centralized Configuration?​

1.1 The Problem Without Config Server​

microservices/
β”œβ”€β”€ user-service/
β”‚ └── application.yml # Specific config
β”œβ”€β”€ product-service/
β”‚ └── application.yml # Specific config
β”œβ”€β”€ order-service/
β”‚ └── application.yml # Specific config
β”œβ”€β”€ payment-service/
β”‚ └── application.yml # Specific config
└── inventory-service/
└── application.yml # Specific config

Problems:

  • Changing the DB password = modifying 5 files
  • Redeploying 5 services
  • No centralized versioning
  • Secrets in plain text in each service
  • No refresh without restart

1.2 The Solution: Config Server​

Advantages:

  • A single source of truth
  • Versioning with Git (history, branches)
  • Refresh without redeployment
  • Encryption of secrets
  • Configuration by environment (dev, prod)

2. Spring Cloud Config Architecture​

2.1 Components​

2.2 Configuration Flow​


3. Config Server Setup​

3.1 Project Structure​

config-server/
β”œβ”€β”€ pom.xml
└── src/main/
β”œβ”€β”€ java/com/example/configserver/
β”‚ └── ConfigServerApplication.java
└── resources/
└── application.yml

3.2 Maven Dependencies​

<?xml version="1.0" encoding="UTF-8"?>
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

<groupId>com.example</groupId>
<artifactId>config-server</artifactId>
<version>1.0.0</version>

<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.0</spring-cloud.version>
</properties>

<dependencies>
<!-- Config Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

<!-- Eureka Client (for registration) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

3.3 Main Application​

package com.example.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer // Enable Config Server
public class ConfigServerApplication {

public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}

3.4 Configuration with Git​

# application.yml
server:
port: 8888

spring:
application:
name: config-server
cloud:
config:
server:
git:
# Git Repository (GitHub, GitLab, Bitbucket, local)
uri: https://github.com/your-org/config-repo
# Default branch
default-label: main
# Folder in the repo (optional)
search-paths: config
# Clone on startup
clone-on-start: true
# Credentials if private repo
username: ${GIT_USERNAME:}
password: ${GIT_PASSWORD:}
# Timeout
timeout: 10

# Eureka Client
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/

# Security
spring:
security:
user:
name: config
password: config123

3.5 Local Configuration (for dev)​

spring:
cloud:
config:
server:
native:
search-locations:
- file:///C:/config-repo
- classpath:/config
profiles:
active: native # Use filesystem instead of Git

4. Configuration Repository Structure​

4.1 Naming Convention​

config-repo/
β”œβ”€β”€ application.yml # Common config for ALL services
β”œβ”€β”€ application-dev.yml # Dev config for ALL services
β”œβ”€β”€ application-prod.yml # Prod config for ALL services
β”œβ”€β”€ user-service.yml # Specific config for user-service
β”œβ”€β”€ user-service-dev.yml # user-service in dev
β”œβ”€β”€ user-service-prod.yml # user-service in prod
β”œβ”€β”€ product-service.yml
β”œβ”€β”€ product-service-dev.yml
β”œβ”€β”€ product-service-prod.yml
β”œβ”€β”€ order-service.yml
β”œβ”€β”€ order-service-dev.yml
└── order-service-prod.yml

4.2 Configuration Priority​

Configuration is merged in this order (from least to most priority):

  1. application.yml (common base)
  2. application-\{profile\}.yml (common profile)
  3. {service-name}.yml (specific service)
  4. {service-name}-\{profile\}.yml (service + profile)

4.3 Example: application.yml (common)​

# config-repo/application.yml
# Shared configuration for ALL services

# Common Eureka
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true

# Common Actuator
management:
endpoints:
web:
exposure:
include: health,info,refresh
endpoint:
health:
show-details: always

# Common Logging
logging:
level:
root: INFO
com.example: DEBUG

4.4 Example: user-service.yml​

# config-repo/user-service.yml
# Specific configuration for User Service

server:
port: 8081

spring:
datasource:
url: jdbc:postgresql://localhost:5432/users_db
username: ${DB_USERNAME:postgres}
password: ${DB_PASSWORD:postgres}
jpa:
hibernate:
ddl-auto: validate
show-sql: false

# Business Configuration
user:
default-role: USER
password-min-length: 8
token-expiration-hours: 24

4.5 Example: user-service-dev.yml​

# config-repo/user-service-dev.yml
# Override for development environment

spring:
datasource:
url: jdbc:h2:mem:users_dev
driver-class-name: org.h2.Driver
h2:
console:
enabled: true
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true

logging:
level:
com.example.userservice: TRACE
org.hibernate.SQL: DEBUG

4.6 Example: user-service-prod.yml​

# config-repo/user-service-prod.yml
# Production configuration

spring:
datasource:
url: jdbc:postgresql://prod-db.example.com:5432/users_db
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
minimum-idle: 5
jpa:
hibernate:
ddl-auto: none
show-sql: false

logging:
level:
root: WARN
com.example: INFO

# Disable sensitive endpoints
management:
endpoints:
web:
exposure:
include: health,info

5. Config Client Setup​

5.1 Maven Dependencies (Service)​

<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<!-- Bootstrap (to load config before app) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

<!-- Eureka Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- Actuator (for /refresh) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

5.2 Client Configuration (Method 1: bootstrap.yml)​

# src/main/resources/bootstrap.yml
# Loaded BEFORE application.yml

spring:
application:
name: user-service # Must match the config file names
profiles:
active: dev
cloud:
config:
# Direct URL of the Config Server
uri: http://localhost:8888
# Credentials if Config Server is secured
username: config
password: config123
# Retry if Config Server is unavailable
fail-fast: true
retry:
initial-interval: 1000
max-attempts: 6
max-interval: 2000
multiplier: 1.1

5.3 Client Configuration (Method 2: application.yml with import)​

# src/main/resources/application.yml
# Spring Boot 2.4+ - no need for bootstrap.yml

spring:
application:
name: user-service
profiles:
active: dev
config:
import: "optional:configserver:http://localhost:8888"
cloud:
config:
username: config
password: config123

5.4 Discovery via Eureka​

# Instead of a fixed URL, discover via Eureka
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server # Name in Eureka
fail-fast: true

eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/

6. Accessing Properties in Code​

6.1 Injection with @Value​

@RestController
@RequestMapping("/api/users")
public class UserController {

@Value("${user.default-role}")
private String defaultRole;

@Value("${user.password-min-length}")
private int passwordMinLength;

@Value("${user.token-expiration-hours}")
private int tokenExpirationHours;

@GetMapping("/config")
public Map<String, Object> getConfig() {
return Map.of(
"defaultRole", defaultRole,
"passwordMinLength", passwordMinLength,
"tokenExpirationHours", tokenExpirationHours
);
}
}

6.2 Injection with @ConfigurationProperties​

package com.example.userservice.config;

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

@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {

private String defaultRole;
private int passwordMinLength;
private int tokenExpirationHours;

// Getters and Setters
public String getDefaultRole() { return defaultRole; }
public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole;
}

public int getPasswordMinLength() { return passwordMinLength; }
public void setPasswordMinLength(int passwordMinLength) {
this.passwordMinLength = passwordMinLength;
}

public int getTokenExpirationHours() { return tokenExpirationHours; }
public void setTokenExpirationHours(int tokenExpirationHours) {
this.tokenExpirationHours = tokenExpirationHours;
}
}
@Service
public class UserService {

private final UserProperties userProperties;

public UserService(UserProperties userProperties) {
this.userProperties = userProperties;
}

public User createUser(UserRequest request) {
User user = new User();
user.setRole(userProperties.getDefaultRole());
// ...
return user;
}
}

7. Hot Configuration Refresh​

7.1 The Problem​

1. Modify user-service-dev.yml in Git
2. Commit & Push
3. Config Server sees the change
4. BUT: user-service still has the old config!
(It loaded it at startup)

7.2 Solution 1: /actuator/refresh Endpoint​

# Expose the refresh endpoint
management:
endpoints:
web:
exposure:
include: health,info,refresh
# Trigger the refresh manually
curl -X POST http://localhost:8081/actuator/refresh

7.3 @RefreshScope Beans​

@RestController
@RequestMapping("/api/config")
@RefreshScope // This bean will be recreated on refresh
public class ConfigController {

@Value("${user.token-expiration-hours}")
private int tokenExpirationHours;

@GetMapping("/token-expiration")
public int getTokenExpiration() {
return tokenExpirationHours;
}
}

7.4 Solution 2: Spring Cloud Bus (Automatic Propagation)​

Dependency:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

Trigger global refresh:

curl -X POST http://config-server:8888/actuator/busrefresh

8. Encryption of Secrets​

8.1 Why Encrypt?​

# ❌ DANGER: Password in plain text in Git!
spring:
datasource:
password: SuperSecret123!

8.2 Encryption Configuration​

# Config Server - application.yml
encrypt:
key: ${ENCRYPT_KEY:my-secret-encryption-key-32chars!}

Or with a keystore:

encrypt:
key-store:
location: classpath:/server.jks
password: keystorepassword
alias: configserver
secret: keypassword

8.3 Encrypting a Value​

# Encrypt
curl -X POST http://localhost:8888/encrypt -d "SuperSecret123!"
# Result: AQB...encodedValue...

# Decrypt (to verify)
curl -X POST http://localhost:8888/decrypt -d "AQB...encodedValue..."
# Result: SuperSecret123!

8.4 Using the Encrypted Value​

# config-repo/user-service-prod.yml
spring:
datasource:
password: '{cipher}AQB...encodedValue...'

The Config Server automatically decrypts before sending to the client.

8.5 Asymmetric Encryption (RSA)​

# Generate a keystore
keytool -genkeypair -alias configserver -keyalg RSA \
-dname "CN=Config Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
-keypass changeme -keystore server.jks -storepass changeme
encrypt:
key-store:
location: file:/etc/config-server/server.jks
password: ${KEYSTORE_PASSWORD}
alias: configserver
secret: ${KEY_PASSWORD}

9. Config Server Endpoints​

9.1 URL Patterns​

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

9.2 Examples​

# Configuration for user-service with dev profile
curl http://localhost:8888/user-service/dev
curl http://localhost:8888/user-service-dev.yml

# Configuration with specific branch
curl http://localhost:8888/user-service/dev/feature-branch

# Configuration in properties format
curl http://localhost:8888/user-service-dev.properties

9.3 JSON Response​

curl http://localhost:8888/user-service/dev
{
"name": "user-service",
"profiles": ["dev"],
"label": "main",
"version": "abc123def456",
"propertySources": [
{
"name": "https://github.com/org/config-repo/user-service-dev.yml",
"source": {
"spring.datasource.url": "jdbc:h2:mem:users_dev",
"user.default-role": "USER"
}
},
{
"name": "https://github.com/org/config-repo/user-service.yml",
"source": {
"server.port": 8081
}
},
{
"name": "https://github.com/org/config-repo/application.yml",
"source": {
"eureka.client.service-url.defaultZone": "http://localhost:8761/eureka/"
}
}
]
}

10. Best Practices​

10.1 Environment Separation​

config-repo/
β”œβ”€β”€ application.yml # NEVER secrets here
β”œβ”€β”€ application-dev.yml # Dev config (can have default values)
β”œβ”€β”€ application-staging.yml # Staging config
β”œβ”€β”€ application-prod.yml # ONLY references to env variables

10.2 Secrets in Production​

# ❌ Bad
spring:
datasource:
password: '{cipher}AQB...' # Even encrypted, it's in Git

# βœ… Good
spring:
datasource:
password: ${DB_PASSWORD} # Environment variable

10.3 Fail-Fast​

spring:
cloud:
config:
fail-fast: true # Service won't start if Config Server unavailable
retry:
max-attempts: 6
initial-interval: 1000

10.4 Appropriate Timeouts​

spring:
cloud:
config:
request-connect-timeout: 5000
request-read-timeout: 10000

10.5 Health Check​

// Health check automatically includes the Config Server
// GET /actuator/health
{
"status": "UP",
"components": {
"configServer": {
"status": "UP",
"details": {
"propertySources": [...]
}
}
}
}

11. Summary​

Key Points​

βœ… Config Server = Single source of configuration
βœ… Git Backend = Versioning, history, branches
βœ… Naming Convention = {service}-\{profile\}.yml
βœ… @RefreshScope = Beans that reload
βœ… Encryption = Secured secrets
βœ… Spring Cloud Bus = Distributed automatic refresh

Startup Order​

  1. Eureka Server (8761) - Service Discovery
  2. Config Server (8888) - Configuration
  3. Other services - Retrieve their config then register

Checklist​

  • Config Server configured with Git
  • Structured configuration repository
  • Clients configured with bootstrap.yml or spring.config.import
  • /refresh endpoint exposed
  • Secrets encrypted or via environment variables
  • fail-fast enabled

Next Chapter: API Gateway β†’

Back to Module 13