Microservices

Implementing Centralized Configuration Using Spring Cloud Config

By Utility Zone · 2025-11-04T15:24:30.512163

Spring Cloud Config provides a centralized server-side solution for managing externalized configuration properties across multiple microservices in a distributed environment. Rather than storing configuration values in individual application properties files, you can maintain them in a central repository (typically Git) and serve them to all client applications dynamically.123


Architecture Overview

The Spring Cloud Config architecture consists of three main components:231

Config Server: A Spring Boot application that reads configuration properties from various backends (Git, local filesystem, databases) and exposes them via REST endpoints to client applications.31

Config Repository: A version-controlled repository (usually Git) where all configuration files are stored, enabling versioning, auditing, and rollback capabilities.42

Config Clients: Microservices that fetch their configuration from the Config Server at startup and can dynamically refresh configurations at runtime.56


Setting Up Spring Cloud Config Server

Step 1: Create the Config Server Project

Start by creating a new Spring Boot project using Spring Initializer with the following configuration:1

Dependencies:

  • Spring Cloud Config Server
  • Spring Boot Actuator (for management endpoints)
  • Spring Web

Add Maven Dependency (pom.xml):

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

Step 2: Enable Config Server

Annotate your main application class with @EnableConfigServer to transform it into a configuration server:31

package com.example.configserver;

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

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

Step 3: Configure Configuration Source

There are multiple ways to store configuration files with Spring Cloud Config Server:3

Option A: Using Git Repository

Configure your Config Server to fetch properties from a Git repository (application.yml):

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/username/config-repo.git
          # For local Git repository:
          # uri: file:///path/to/local/config-repo
          username: your-username
          password: your-password
          # Or use SSH:
          # uri: git@github.com:username/config-repo.git

server:
  port: 8888

Option B: Using Local File System

For development or testing, store configurations locally:3

spring:
  application:
    name: config-server
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          search-locations: file:///C:/Documents/config, file:///D:/config-backup

server:
  port: 8888

Option C: Multiple Configuration Sources

Combine Git and local filesystem sources:3

spring:
  application:
    name: config-server
  profiles:
    active: native, git
  cloud:
    config:
      server:
        native:
          search-locations: file:///C:/Documents/config
        git:
          uri: https://github.com/username/config-repo.git
        repos:
          testapp:
            pattern: test-app
            uri: https://github.com/username/test-app-config.git

Step 4: Create Configuration Repository

If using Git, initialize a Git repository and add configuration files named after your microservices:4

cd config-repo
git init

Create property files (application.properties, microservice-specific files):

# application.properties (shared by all services)
logging.level.root=INFO
spring.jpa.show-sql=true

# employee-service.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/employee_db
spring.datasource.username=root
spring.datasource.password=root

# employee-service-dev.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/employee_dev
logging.level.root=DEBUG

# department-service.properties
server.port=8082
spring.datasource.url=jdbc:mysql://localhost:3306/department_db

Commit and push to the repository:

git add .
git commit -m "Initial configuration"
git push origin main

Step 5: Test Config Server

Run the Config Server and access the configuration via REST endpoints:1

http://localhost:8888/employee-service/dev
http://localhost:8888/employee-service/main
http://localhost:8888/application/prod

The response includes all applicable property sources for the requested service and profile.1


Setting Up Config Clients

Step 1: Create a Microservice Project

Create a new Spring Boot project with these dependencies:76

Dependencies:

  • Spring Cloud Config Client
  • Spring Web
  • Spring Boot Actuator

Add Maven Dependency (pom.xml):

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Step 2: Configure Client Application Properties

In your client application, configure the connection to the Config Server. Create an application.properties file:67

spring.application.name=employee-service
spring.config.import=configserver:http://localhost:8888
spring.profiles.active=dev
server.port=8081
management.endpoints.web.exposure.include=health,info,refresh

Key properties explained:

  • spring.application.name: Identifies which configuration file to fetch from Config Server (must match filename in repository)
  • spring.config.import: Location of the Config Server
  • spring.profiles.active: Specifies which profile-specific configuration to load (dev, prod, test, etc.)
  • management.endpoints.web.exposure.include: Exposes actuator endpoints for dynamic refresh6

Step 3: Access Configuration Properties

Inject configuration properties using @Value annotation:76

package com.example.employeeservice;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {
    
    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    
    @Value("${logging.level.root:INFO}")
    private String logLevel;
    
    @GetMapping("/config")
    public String getConfig() {
        return "Database URL: " + datasourceUrl + 
               ", Log Level: " + logLevel;
    }
}

Dynamic Configuration Refresh

By default, configuration properties are loaded only once at application startup. To enable dynamic refresh without restarting the application, use one of these approaches:8910

Approach 1: Using Actuator /refresh Endpoint (Manual Refresh)

Annotate your bean with @RefreshScope to mark it as refreshable:119

package com.example.employeeservice;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class EmployeeController {
    
    @Value("${spring.datasource.username}")
    private String dbUsername;
    
    @GetMapping("/username")
    public String getUsername() {
        return "Current username: " + dbUsername;
    }
}

When you update the configuration in the Git repository and commit, trigger a refresh by sending a POST request:9

curl -X POST http://localhost:8081/actuator/refresh

The @RefreshScope annotation ensures that the @Value properties are re-evaluated after the refresh is triggered.119

Approach 2: Using Spring Cloud Bus (Automatic Refresh)

For multi-instance scenarios where you need to refresh all service instances automatically, use Spring Cloud Bus with a message broker:109

Add dependencies (pom.xml):

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

Configure RabbitMQ (application.yml):

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

management:
  endpoints:
    web:
      exposure:
        include: busrefresh,refresh

Trigger refresh across all instances:10

curl -X POST http://localhost:8081/actuator/bus-refresh

Property Loading Precedence

Understanding the order in which properties are loaded is crucial for effective configuration management:121314

Loading Order (highest to lowest priority):

  1. Profile-specific files (e.g., application-dev.properties) override non-specific files13
  2. Application-specific profile files (e.g., employee-service-dev.properties) override shared profile files13
  3. Application-specific files (e.g., employee-service.properties) override shared files13
  4. Shared profile files (e.g., application-dev.properties) override shared files13
  5. Shared files (e.g., application.properties)13
  6. Local properties have higher precedence than Config Server properties14

Properties file format precedence:

  • .properties files have higher priority than .yaml files13

For multiple active profiles (e.g., spring.profiles.active=dev,local), properties are applied using a last-win strategy where the rightmost profile has the highest precedence.13


Securing Sensitive Data with Encryption

Spring Cloud Config supports encryption of sensitive properties like database passwords and API keys:151617

Symmetric Encryption Setup

1. Enable Encryption (application.yml):

encrypt:
  enabled: true
  key: my-secret-encryption-key-12345

2. Encrypt Sensitive Properties

Send a POST request to the Config Server's encrypt endpoint to encrypt values:15

curl -X POST http://localhost:8888/encrypt -d "password123"

Response: b4fb33fd916f2a3e92c5eaaf92d5dbd0c7a74e1bc20f1234567890abcdef

3. Store Encrypted Value in Configuration

In your Git repository, prefix encrypted values with {cipher}:

# employee-service.properties
spring.datasource.password={cipher}b4fb33fd916f2a3e92c5eaaf92d5dbd0c7a74e1bc20f1234567890abcdef

4. Decryption Happens Automatically

When the client fetches configuration, Spring Cloud Config automatically decrypts values with the {cipher} prefix using the encryption key.1615

Asymmetric Encryption (RSA) Setup

For enhanced security using public/private key pairs:1715

1. Generate Key Pair:

keytool -genkeypair -alias config-server -keyalg RSA -keystore config-server.jks -storepass password

2. Configure Server (application.yml):

encrypt:
  key-store:
    location: classpath:config-server.jks
    password: password
    alias: config-server
    secret: password

3. Client Configuration (application.properties):

Clients automatically decrypt using the public key information from the server without needing the private key.1715


Configuration File Organization Best Practices

For optimal configuration management across microservices:3

Directory Structure:

config-repo/
├── application.properties          (shared across all services)
├── application-dev.properties      (shared, development profile)
├── application-prod.properties     (shared, production profile)
├── employee-service.properties
├── employee-service-dev.properties
├── employee-service-prod.properties
├── department-service.properties
├── department-service-dev.properties
└── department-service-prod.properties

Naming Convention:

Use {application-name}-{profile}.properties format where:

  • {application-name} matches spring.application.name in your microservice
  • {profile} corresponds to spring.profiles.active186

Complete Example Workflow

1. Update Configuration in Git:

Edit employee-service-dev.properties and change:

logging.level.root=DEBUG

Commit and push:

git add employee-service-dev.properties
git commit -m "Update logging level to DEBUG"
git push origin main

2. Trigger Refresh in Running Service:

curl -X POST http://localhost:8081/actuator/refresh

3. Verify Changes:

curl http://localhost:8081/config

The response now shows the updated configuration values without restarting the application.89


Key Advantages of Spring Cloud Config

Centralized Management: All configurations stored in one location, reducing duplication and inconsistency.23

Version Control: Git-based storage enables tracking changes, auditing, and rolling back to previous configurations.23

Environment-Specific Configurations: Easily manage different settings for development, testing, and production environments without code changes.83

Dynamic Updates: Configurations refresh without restarting applications, minimizing downtime.98

Security: Built-in encryption support protects sensitive data like credentials and API keys.161517

Scalability: Designed for distributed systems with support for multiple microservices across many environments.83

Spring Cloud Config, combined with Spring Boot and proper configuration practices, provides a robust foundation for managing complex microservices configurations across entire organizations. <span style="display:none">1920</span>


<div align="center">⁂</div>

Footnotes

  1. https://www.tutorialspoint.com/spring_boot/spring_boot_cloud_configuration_server.htm ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  2. https://www.geeksforgeeks.org/advance-java/using-git-as-a-backend-for-spring-cloud-config-server/ ↩ ↩2 ↩3 ↩4 ↩5

  3. https://www.ideas2it.com/blogs/use-spring-cloud-config-to-centralize-your-spring-applications ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12

  4. https://dzone.com/articles/how-to-setup-the-spring-cloud-configuration-server-with-git ↩ ↩2

  5. https://docs.spring.io/spring-cloud-config/reference/client.html ↩

  6. https://dzone.com/articles/setting-up-spring-cloud-config-client ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  7. https://mobisoftinfotech.com/resources/blog/web-programming/tutorial-spring-cloud-config-server-and-client-how-to-set-up-spring-cloud-config-with-jdbc-in-your-microservices-project ↩ ↩2 ↩3

  8. https://www.geeksforgeeks.org/advance-java/dynamic-configuration-updates-with-spring-cloud-config/ ↩ ↩2 ↩3 ↩4 ↩5

  9. https://www.devglan.com/spring-cloud/refresh-property-config-runtime ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  10. https://www.javacodegeeks.com/2018/03/refresh-property-config-at-runtime-in-spring-cloud-config.html ↩ ↩2 ↩3

  11. https://keyholesoftware.com/centralizing-configurations-with-spring-cloud-config/ ↩ ↩2

  12. https://stackoverflow.com/questions/68672549/spring-cloud-config-precedence-property-files ↩

  13. https://bkjam.github.io/posts/2022-06-21-5-observations-on-spring-boot-loading-precedence-for-properties-files-with-spring-cloud-config/ ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8

  14. https://codingtechroom.com/question/spring-cloud-config-property-loading-precedence ↩ ↩2

  15. https://www.mymiller.name/wordpress/spring_config/secure-your-secrets-encrypting-values-with-spring-cloud-config/ ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  16. https://www.geeksforgeeks.org/advance-java/encrypting-sensitive-configuration-data-in-spring-cloud-config/ ↩ ↩2 ↩3

  17. https://www.mymiller.name/wordpress/spring_config/spring-cloud-config-encryption-securing-your-sensitive-data/ ↩ ↩2 ↩3 ↩4

  18. https://www.geeksforgeeks.org/advance-java/implementing-configuration-versioning-with-spring-cloud-config/ ↩

  19. https://techdocs.broadcom.com/us/en/vmware-tanzu/spring/spring-cloud-services-for-cloud-foundry/3-2/scs-tanzu/config-server-configuring-with-git.html ↩

  20. https://spring.io/guides/gs/centralized-configuration/ ↩