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):
application.yml(common base)application-\{profile\}.yml(common profile){service-name}.yml(specific service){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β
- Eureka Server (8761) - Service Discovery
- Config Server (8888) - Configuration
- 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