Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 119 ยท Spring Cloud

Centralized Configuration with Spring Cloud Config

Serve configuration for many services from Git with Spring Cloud Config. Learn profiles, labels, client import, refresh, Spring Cloud Bus, secrets and ConfigMaps.

A single Spring Boot application keeps its settings in application.yml, environment variables and command-line arguments, as you saw in Configuration, Properties and Profiles. That works well for one service. With twenty services, each running in dev, test and prod, it stops working: the same database host is copied into a dozen files, nobody can tell which version of a setting is live, and changing a timeout means rebuilding and redeploying a JAR.

Spring Cloud Config moves configuration out of the services into one place, usually a Git repository. A small Config Server reads that repository and serves properties over HTTP; every service fetches its settings at startup. You get history and code review for configuration changes (they are commits), one place to look, and the option to change some settings without a redeploy.

The Microservices lesson introduced the idea in one paragraph. This lesson goes all the way: how the server finds files, how the client merges remote values with local ones, how refreshing works, and how to keep secrets safe. As in the rest of this track, the runnable examples rebuild each mechanism in plain Java (Spring Cloud isn't available in our code runner), and the real server and client code is shown read-only.

How the Config Server finds your properties

A client asks for three things: the application name (spring.application.name, such as orders), one or more profiles (prod, dev) and a label, which for a Git backend is a branch, tag or commit id (default main). The main endpoints are:

TEXT
GET /{application}/{profile}[/{label}]          JSON with all matching property sources
GET /{application}-{profile}.yml                one merged YAML document
GET /{label}/{application}-{profile}.properties one merged properties file

For GET /orders/prod, the server looks in the repository for these files, most specific first:

Priority File Holds
1 orders-prod.yml Settings for orders in production
2 application-prod.yml Settings shared by every service in production
3 orders.yml Settings for orders in every environment
4 application.yml Defaults shared by every service

A key found in a higher file wins. That layout lets you write a shared value once (application.yml) and override it only where needed. The JSON response lists the sources in exactly this order, so the client can merge them.

The next program is a tiny Config Server. An in-memory map stands in for the Git repository, with two labels: main and a release-2.4 branch. The server answers /{application}/{profile}/{label} with JSON shaped like the real one, and a client fetches its configuration and resolves keys by taking the first source that has them.

Java A mini Config Server with profiles and labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In production, orders.payment-timeout comes from orders-prod.properties (800ms), the page size from orders.properties and the log level from application-prod.properties. On the release-2.4 branch only one file exists, so the other keys are not set by the server at all, and the client's local defaults would apply. An unknown label gives 404; the real server answers the same way when a branch doesn't exist.

The real Config Server

The server is an ordinary Spring Boot application with one extra starter and one annotation:

XML
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-config-server</artifactId>
</dependency>
Java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
YAML
server:
  port: 8888                         # the conventional Config Server port
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/acme/config-repo
          default-label: main
          search-paths: '{application}'  # optional: one folder per service
          clone-on-start: true           # fail at startup, not on the first request
          username: config-reader
          password: ${GIT_TOKEN}         # a read-only token from the environment

Spring Cloud dependency versions come from the release train BOM (spring-cloud-dependencies), not from individual version numbers. Check the current release train that matches your Spring Boot version (for Spring Boot 4 that is 2025.1, "Oakwood").

Spring Cloud Config reads Git (and Subversion, in older setups) through the same repository abstraction: a Subversion backend is selected with spring.profiles.active=subversion and spring.cloud.config.server.svn.uri, and the "label" becomes a branch or trunk path. For development without any repository, the native profile (spring.profiles.active=native) reads files from disk, and spring.cloud.config.server.native.search-locations lists the folders, such as classpath:/config or file:///opt/config/{application}. The same placeholder idea (, , ) works in Git search-paths and in native search-locations.

Git is the most common backend, but not the only one. The server also reads from a local folder (native profile, handy for development), HashiCorp Vault, a JDBC table, AWS S3, AWS Secrets Manager and Parameter Store, and composite setups that combine several of them with an order.

The client side

A service adds spring-cloud-starter-config and imports the server in its own application.yml:

YAML
spring:
  application:
    name: orders                     # selects orders.yml and orders-{profile}.yml
  profiles:
    active: prod
  config:
    import: "optional:configserver:http://config-server:8888"
  cloud:
    config:
      label: main
      fail-fast: false

spring.config.import is the modern way. Older applications used a separate bootstrap.yml read by a "bootstrap context" before the main one; that mode still exists behind spring-cloud-starter-bootstrap, but new code shouldn't need it.

The imported property sources slot into Spring Boot's normal order just above the local file that imported them. Remote values therefore beat the application.yml inside the JAR, while command-line arguments, system properties and environment variables still beat everything. That is useful: an operator can still override a remote value for one instance with an environment variable.

The next example merges four layers the way a client does and reports where each value came from, like the /actuator/env endpoint.

Java How a client merges remote and local configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The payment timeout shows the subtle part. The server says 800ms, but this instance was started with an environment variable ORDERS_PAYMENTTIMEOUT=1500ms, so the environment wins. When someone reports "I changed it in Git and nothing happened", check for an environment override first.

When the Config Server is down

The optional: prefix decides what happens if the server can't be reached at startup:

  • optional:configserver:...: log a warning and start with local configuration only. Good for development, risky in production, because the service may start with defaults such as an H2 database.
  • configserver:... without optional:: startup fails if the server is unreachable.
  • spring.cloud.config.fail-fast=true plus spring-retry on the classpath: retry a few times with backoff before failing. Defaults are 6 attempts, starting at 1 second and growing by a factor of 1.1, capped at 2 seconds (spring.cloud.config.retry.*).

Retrying matters when the whole system starts at once, for example after a cluster restart, and services race the Config Server. This program reproduces that race with fast timings: the server only comes up after the client has tried three times.

Java Fail-fast with retry while the Config Server starts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first three attempts fail with ConnectException, and the waits grow from 100 ms to 150 ms and 225 ms. To keep the demo repeatable, the server "finishes starting" right after the third failure, so the fourth attempt loads the configuration. Without retries and without optional:, the service would have crashed on the first attempt; with optional: it would have started silently with the wrong settings.

Changing configuration without a redeploy

Most properties are read once, when beans are created. To change values in a running service, Spring Cloud offers refresh:

  1. Someone commits a change to the config repository.
  2. Each instance receives POST /actuator/refresh (expose the refresh endpoint first).
  3. The instance re-reads its property sources, compares old and new values, and publishes an EnvironmentChangeEvent with the changed keys. The endpoint returns them as a JSON array.
  4. @ConfigurationProperties beans are rebound with the new values automatically.
  5. Beans annotated with @RefreshScope are thrown away and created again, lazily, on their next use, so constructor logic and @Value fields see the new values.
Java
@RestController
@RefreshScope
class PromoController {

    private final String banner;

    PromoController(@Value("${promo.banner:}") String banner) {
        this.banner = banner;              // read once per bean instance
    }

    @GetMapping("/promo")
    String promo() {
        return banner;
    }
}

Calling every instance by hand doesn't scale. Spring Cloud Bus connects all instances through RabbitMQ or Kafka: one POST /actuator/busrefresh to any instance broadcasts a refresh event that every instance (or only those of one service, with a destination) handles. With the spring-cloud-config-monitor module, the Config Server itself can receive a Git webhook on /monitor and publish the bus event, so a git push updates the whole fleet.

This program rebuilds the mechanism: three instances share a bus, each has a refresh scope holding a lazily created bean and an ordinary singleton that copied a value at startup.

Java RefreshScope and a broadcast refresh over a bus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the last lines. The refresh-scoped Banner bean was recreated on first use after the refresh and shows the new text. The environment has the new page size too. But the ordinary singleton still says 20: it copied the value into a field at startup and nobody told it. That is the classic refresh bug. Use @ConfigurationProperties (rebound automatically) or @RefreshScope for anything that must change at runtime, and accept that some things never refresh safely: a DataSource URL or a server port needs a restart.

Refresh is powerful and easy to misuse. A bad commit reaches every instance within seconds, with no build, test or canary in between. Many teams therefore refresh only feature flags and tuning values, and roll out everything else with a normal restart, which is also what Kubernetes does best.

Secrets

A Git repository full of plaintext passwords is a breach waiting to happen. You have three common options:

  • Encrypted values in Git. The Config Server has /encrypt and /decrypt endpoints. You store '{cipher}...' values, and the server decrypts them before sending them to clients (or the clients decrypt, if spring.cloud.config.server.encrypt.enabled=false). The key is either a symmetric key (ENCRYPT_KEY environment variable) or an RSA key pair in a keystore.
  • A secret store. HashiCorp Vault as a Config Server backend, or directly from each service with Spring Cloud Vault (spring.config.import=vault://). Vault adds access policies, auditing and short-lived, automatically rotated database credentials.
  • Platform secrets. Kubernetes Secrets or a cloud secret manager, mounted as files or environment variables.
YAML
# orders-prod.yml in the config repository
spring:
  datasource:
    username: orders
    password: '{cipher}AQBj5mS0...'   # quote it: YAML would read { as the start of a map

The next program shows the idea of server-side decryption with the JDK's AES-GCM. The real server uses its own cipher format, so these values aren't interchangeable with it, but the flow is the same: the repository only ever holds ciphertext, and only the server holds the key.

Java Encrypted {cipher} values decrypted by the server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Encryption at rest is only part of the job. The decrypted values travel from the server to clients, so protect the Config Server itself: HTTPS, authentication (Spring Security with basic auth or OAuth 2 client credentials), and a network that only your services can reach. Anyone who can call /orders/prod can read the production database password.

Kubernetes ConfigMaps as the alternative

On Kubernetes, many teams skip the Config Server. A ConfigMap holds non-secret settings, a Secret holds secret ones, and both are mounted into the pod as environment variables or files that Spring Boot reads natively:

YAML
apiVersion: v1
kind: ConfigMap
metadata:
  name: orders-config
data:
  application.yaml: |
    orders:
      page-size: 30
      payment-timeout: 800ms

Mount it at /config in the container, and Boot picks it up because ./config/ next to the working directory is one of its default locations (or point spring.config.import=optional:configtree:/etc/secrets/ at mounted Secret files). Changes roll out with a rolling restart, which is predictable and easy to roll back. Spring Cloud Kubernetes can also read ConfigMaps through the Kubernetes API and trigger refreshes, if you really need live reloads.

Spring Cloud Config Kubernetes ConfigMaps/Secrets
Source of truth Git repository (or Vault, JDBC, ...) Kubernetes objects, often generated from Git by Helm, Kustomize or GitOps tools
Works outside Kubernetes Yes No
Live refresh @RefreshScope, actuator refresh, Spring Cloud Bus Usually a rolling restart
Extra infrastructure A Config Server (highly available) plus a bus None
Languages Any client that speaks HTTP, best with Spring Any

Choose one approach per system. Mixing both without a clear rule produces exactly the "where does this value come from?" confusion that centralized configuration was supposed to remove.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client with spring.application.name=orders and profile prod asks the Config Server. The repository has application.yml (timeout 5s), application-prod.yml (timeout 3s) and orders.yml (timeout 4s). Which timeout does the client get?

    The order is orders-prod, application-prod, orders, application. There is no orders-prod.yml, so application-prod.yml (3s) is the most specific file that has the key.
  2. 2. You change promo.banner in Git and call POST /actuator/refresh. A plain singleton copied the value into a field in its constructor. What does it show afterwards?

    Refresh updates the Environment, rebinds @ConfigurationProperties and recreates @RefreshScope beans. Values that other beans copied at startup stay stale.
  3. 3. A service uses spring.config.import=optional:configserver:http://config:8888 and the Config Server is down at startup. What happens?

    The optional prefix makes the import non-fatal. Without it, startup fails; with fail-fast and spring-retry, it retries a few times first.
  4. 4. The Config Server serves payment-timeout=800ms, but one instance runs with the environment variable ORDERS_PAYMENTTIMEOUT=1500ms. Which value does that instance use?

    Imported config sources sit just above the importing file, so environment variables, system properties and command-line arguments still override them.
  5. 5. Why should '{cipher}...' values be quoted in YAML files?

    In YAML, { opens a flow mapping. Quoting keeps the whole value a string so the server can recognize the {cipher} prefix.

Summary

  • Spring Cloud Config serves configuration for many services from one place, usually a Git repository, so changes are versioned and reviewed.
  • Clients request /{application}/{profile}/{label}; sources are ordered -{profile}, application-{profile}, , application, and the first match wins. Labels select a branch, tag or commit.
  • The server is a Boot app with @EnableConfigServer; clients use spring.config.import=configserver:.... Imported values beat local files but not environment variables or command-line arguments.
  • Without optional: a missing server stops startup; fail-fast with spring-retry retries with backoff first.
  • Refresh updates the Environment, rebinds @ConfigurationProperties and recreates @RefreshScope beans; Spring Cloud Bus broadcasts it to all instances. Values copied at startup stay stale.
  • Keep secrets out of plaintext: values, Vault, or platform secrets, and secure the Config Server itself.
  • On Kubernetes, ConfigMaps and Secrets with rolling restarts are a simpler alternative.

Next: Circuit Breakers and Resilience with Resilience4j