Spring Cloud Config and externalised configuration

Configuration that differs between environments belongs outside the jar, and with many services it often belongs in one place. Spring Boot's config data imports, Kubernetes-style secret files and Spring Cloud Config Server are three ways to get it there. This page runs the import mechanisms they all build on, shows the Config Server and client setup, and demonstrates why changing a property at run time does not change a running bean.

Contents

Where configuration comes from

A Spring Boot application reads its settings from an ordered list of property sources in its Environment: command-line arguments, system properties, environment variables, application.yml files and anything those files import. When two sources define the same key, the one higher in the list wins. Every @Value field and @ConfigurationProperties class is filled from that list when its bean is created.

With one service, application.yml in the jar plus environment variables per environment is usually enough. With dozens of services, teams want shared settings in one place, a history of every change, and sometimes a way to change a value without redeploying. That is what a configuration server offers. Since Spring Boot 2.4, all of these sources are plugged in the same way, through spring.config.import:

Ways to supply configuration to a Spring Boot application
SourceImport or mechanismBest for
Files next to the jar or in a mounted volumefile:, optional:file:Settings per environment, deployed with the application
One file per key, as Kubernetes mounts Secretsconfigtree:Secrets and ConfigMaps on Kubernetes
Environment variablesBuilt in, relaxed binding (SHOP_TAX_RATE)A few values per deployment, containers
Spring Cloud Config Serverconfigserver:Central, versioned configuration for many services, from Git
HashiCorp Vault, AWS Parameter Store or Secrets Managervault://, aws-parameterstore:, aws-secretsmanager:Secrets with access control and rotation

Spring Cloud Config is part of the Spring Cloud release train. For Spring Boot 4.1 that is Spring Cloud 2025.1, and the programs on this page use Spring Cloud Config 5.0.5. All five run as shown: the first two use Spring Boot's own imports, the next two start a real Config Server and a client against it in one program, and the last one shows the refresh problem without Spring Cloud. The page's classpath holds spring-cloud-config-server and spring-boot-starter-actuator for every program.

Importing configuration files

A shop keeps its shared settings in one file and an override for its European deployment in another, both outside the jar. The program writes the two files to a temporary directory, imports them along with an optional file that does not exist, and passes one value on the command line:

Java
package demo.config.imports;

import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;

public class ConfigImport {

    @SpringBootConfiguration
    static class ShopApplication {
    }

    public static void main(String[] args) throws Exception {
        // stand-ins for configuration that lives outside the application jar
        Path dir = Files.createTempDirectory("shop-config");
        Files.writeString(dir.resolve("shared.yml"), """
                shop:
                  currency: EUR
                  tax-rate: 0.21
                  support-email: help@example.com
                """);
        Files.writeString(dir.resolve("eu-override.properties"), "shop.tax-rate=0.19\n");

        String imports = "file:" + dir.resolve("shared.yml")
                + ",optional:file:" + dir.resolve("not-there.yml")
                + ",file:" + dir.resolve("eu-override.properties");
        SpringApplication app = new SpringApplication(ShopApplication.class);
        try (var context = app.run("--spring.main.banner-mode=off",
                "--logging.level.root=OFF", "--spring.main.web-application-type=none",
                "--spring.config.import=" + imports,
                "--shop.support-email=eu-help@example.com")) {
            ConfigurableEnvironment env = context.getEnvironment();
            for (String key : new String[] {"shop.currency", "shop.tax-rate",
                    "shop.support-email"}) {
                System.out.printf("%-19s = %s%n", key, env.getProperty(key));
            }
            System.out.println("Property sources, highest precedence first:");
            for (PropertySource<?> source : env.getPropertySources()) {
                System.out.println("  " + source.getName().replace(dir.toString(), "<dir>"));
            }
        }

        try (var context = app.run("--spring.main.banner-mode=off",
                "--logging.level.root=OFF", "--spring.main.web-application-type=none",
                "--spring.config.import=file:" + dir.resolve("not-there.yml"))) {
            System.out.println("started with " + context.getBeanDefinitionCount() + " beans");
        } catch (ConfigDataResourceNotFoundException e) {
            System.out.println("Import without optional: "
                    + e.getClass().getSimpleName() + " for "
                    + e.getResource().toString().replace(dir.toString(), "<dir>"));
        }
    }
}
Output
shop.currency       = EUR
shop.tax-rate       = 0.19
shop.support-email  = eu-help@example.com
Property sources, highest precedence first:
  configurationProperties
  commandLineArgs
  systemProperties
  systemEnvironment
  random
  cachedrandom
  configServerClient
  Config resource 'file [<dir>/eu-override.properties]' via location 'file:<dir>/eu-override.properties'
  Config resource 'file [<dir>/shared.yml]' via location 'file:<dir>/shared.yml'
  springCloudClientHostInfo
  applicationInfo
Import without optional: ConfigDataResourceNotFoundException for file [<dir>/not-there.yml]
  • shop.currency came from shared.yml, the only source that defines it.
  • shop.tax-rate is 0.19, not 0.21: both files define it, and of several imports, the later one wins. The list of sources shows why: eu-override.properties sits above shared.yml.
  • shop.support-email came from the command line, which is near the top of the list, above every imported file.
  • cachedrandom, configServerClient and springCloudClientHostInfo come from Spring Cloud, which is on this page's classpath. A plain Spring Boot application shows the same list without them. None of them defines a shop key, so they change nothing here.
  • The optional: import of not-there.yml was silently skipped. The same import without optional: stopped the application with ConfigDataResourceNotFoundException.

The failure is the right default for configuration the application cannot run without: an application that starts with half its settings is worse than one that does not start. Use optional: only for files that are genuinely optional, such as a developer's local overrides.

Secrets as files with configtree

Kubernetes mounts a Secret or ConfigMap as a directory with one file per key, and the file's content is the value. A configtree: import turns such a directory into properties. The program builds that layout, including a value with a trailing newline, as editors and echo often leave one:

Java
package demo.config.tree;

import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.core.env.Environment;

public class ConfigTree {

    @SpringBootConfiguration
    static class ShopApplication {
    }

    public static void main(String[] args) throws Exception {
        // the layout Kubernetes creates when a Secret is mounted as a volume:
        // one file per key, the file content is the value
        Path mount = Files.createTempDirectory("secrets");
        Files.createDirectories(mount.resolve("db"));
        Files.writeString(mount.resolve("db/username"), "shop_app");
        Files.writeString(mount.resolve("db/password"), "s3cr3t\n");   // note the newline
        Files.writeString(mount.resolve("payment.api-key"), "pk_live_123");

        try (var context = new SpringApplication(ShopApplication.class).run(
                "--spring.main.banner-mode=off", "--logging.level.root=OFF",
                "--spring.main.web-application-type=none",
                "--spring.config.import=configtree:" + mount + "/")) {
            Environment env = context.getEnvironment();
            for (String key : new String[] {"db.username", "db.password", "payment.api-key"}) {
                System.out.printf("%-15s = [%s]%n", key, env.getProperty(key));
            }
        }
    }
}
Output
db.username     = [shop_app]
db.password     = [s3cr3t]
payment.api-key = [pk_live_123]
  • The file db/username became the property db.username: directory levels become the dots of the property name.
  • The file name payment.api-key, which already contains a dot, became payment.api-key as well, so both layouts work.
  • db.password is s3cr3t without the newline, as the brackets show. The import strips the trailing newline, which otherwise causes "wrong password" errors that are very hard to see.

Mounting secrets as files, instead of passing them as environment variables, keeps them out of process listings and crash dumps, and Kubernetes can update the files when the Secret changes. The import reads the files once at start-up, though, so a changed file only takes effect after a restart, or after a refresh as described below.

Spring Cloud Config Server

The Config Server is a small Spring Boot application that serves configuration over HTTP. In production its files usually come from a Git repository. The native profile reads them from a directory or the classpath instead, which needs no Git server, so this program uses it. It writes three files to a temporary directory, starts the server on a random port and asks it for the orders service's configuration:

Java
package demo.config.server;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.cloud.config.server.EnableConfigServer;

public class ConfigServerNative {

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @EnableConfigServer
    static class ConfigServerApplication {
    }

    public static void main(String[] args) throws Exception {
        // the configuration repository: shared defaults plus files for one service
        Path repo = Files.createTempDirectory("config-repo");
        Files.writeString(repo.resolve("application.yml"), """
                shop:
                  currency: EUR
                  tax-rate: 0.21
                """);
        Files.writeString(repo.resolve("orders.yml"), "orders:\n  max-items: 50\n");
        Files.writeString(repo.resolve("orders-prod.yml"), "shop:\n  tax-rate: 0.19\n");

        try (var server = new SpringApplication(ConfigServerApplication.class).run(
                "--server.port=0", "--spring.profiles.active=native",
                "--spring.cloud.config.server.native.search-locations=file:" + repo + "/",
                "--spring.main.banner-mode=off", "--logging.level.root=WARN")) {
            int port = ((WebServerApplicationContext) server).getWebServer().getPort();
            String base = "http://localhost:" + port;
            HttpClient http = HttpClient.newHttpClient();
            String[] paths = {"/orders/prod", "/orders/default", "/orders-prod.yml"};
            for (String path : paths) {
                HttpResponse<String> response = http.send(
                        HttpRequest.newBuilder(URI.create(base + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("GET " + path + " -> " + response.statusCode());
                // the temporary directory name changes on every run
                String body = response.body().replace("file:" + repo + "/", "repo/");
                System.out.println(body.replace("},{", "},\n {").strip());
                System.out.println();
            }
        }
    }
}
Output
GET /orders/prod -> 200
{"name":"orders","profiles":["prod"],"label":null,"version":null,"state":null,"propertySources":[{"name":"repo/orders-prod.yml","source":{"shop.tax-rate":0.19}},
 {"name":"repo/orders.yml","source":{"orders.max-items":50}},
 {"name":"repo/application.yml","source":{"shop.currency":"EUR","shop.tax-rate":0.21}}]}

GET /orders/default -> 200
{"name":"orders","profiles":["default"],"label":null,"version":null,"state":null,"propertySources":[{"name":"repo/orders.yml","source":{"orders.max-items":50}},
 {"name":"repo/application.yml","source":{"shop.currency":"EUR","shop.tax-rate":0.21}}]}

GET /orders-prod.yml -> 200
shop:
  currency: EUR
  tax-rate: 0.19
orders:
  max-items: 50
  • The request GET /orders/prod has the form /{application}/{profile}, with an optional /{label} for a Git branch, tag or commit. The answer listed three files: orders-prod.yml, orders.yml and application.yml, most specific first.
  • The server does not merge the files: it returns each one as a separate property source and leaves the merging to the client. shop.tax-rate appears twice, as 0.19 and 0.21, and the client takes the first one, 0.19.
  • With the default profile, orders-prod.yml dropped out and only two sources remained. application.yml appears in both answers, because it holds what every service shares.
  • label and version are null because a plain directory has no branches or commits. With the Git backend, version holds the commit id, so a client can log exactly which revision of its configuration it runs with.
  • GET /orders-prod.yml returned the same configuration already merged into one YAML document, with tax-rate 0.19. The server also offers .properties and .json, which suits scripts and non-Spring clients.

The program prints repo/ in place of the temporary directory, whose name changes on every run. A server for real use differs in its application.yml and in its dependency, spring-cloud-config-server; the Java class stays as small as above, with @EnableConfigServer:

YAML
server:
  port: 8888
spring:
  cloud:
    config:
      server:
        git:
          uri: https://git.example.com/platform/config.git
          search-paths: '{application}'
          clone-on-start: true
  • Git gives every change an author, a review and a history, and rolling back a bad setting is a revert. That is the main reason to use the Git backend over the others, such as a file system, JDBC or Vault. The Git example was not run here, since it needs a Git server.
  • The server must be secured, for example with Spring Security and HTTP Basic or mutual TLS, because it serves every service's configuration. The program above has no security at all. Values prefixed with {cipher} are stored encrypted in Git and decrypted by the server with the key in encrypt.key or a key store.

The Config client

A service reads from the server with one import, the same mechanism as the file imports above. This program starts the server again, then an orders service with the prod profile that imports its configuration from it. The service holds the tax rate in four kinds of beans. The program then changes orders-prod.yml and asks the service to refresh, as an operator would:

Java
package demo.config.client;

import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

public class ConfigClientRefresh {

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @EnableConfigServer
    static class ConfigServerApplication {
    }

    // mutable: rebound in place on refresh
    @ConfigurationProperties("shop")
    public static class ShopSettings {
        private BigDecimal taxRate;
        public BigDecimal getTaxRate() { return taxRate; }
        public void setTaxRate(BigDecimal taxRate) { this.taxRate = taxRate; }
    }

    // immutable: bound once through the constructor
    @ConfigurationProperties("shop")
    record ShopRecord(BigDecimal taxRate) {
    }

    public static class TaxCalculator {
        @Value("${shop.tax-rate}")
        private BigDecimal taxRate;
        public BigDecimal taxRate() { return taxRate; }
    }

    public static class PlainCalculator {
        @Value("${shop.tax-rate}")
        private BigDecimal taxRate;
        public BigDecimal taxRate() { return taxRate; }
    }

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @EnableConfigurationProperties({ShopSettings.class, ShopRecord.class})
    static class OrdersApplication {
        @Bean
        @RefreshScope
        TaxCalculator taxCalculator() {
            return new TaxCalculator();
        }

        @Bean
        PlainCalculator plainCalculator() {
            return new PlainCalculator();
        }
    }

    public static void main(String[] args) throws Exception {
        Path repo = Files.createTempDirectory("config-repo");
        Files.writeString(repo.resolve("application.yml"), "shop:\n  tax-rate: 0.21\n");
        Files.writeString(repo.resolve("orders-prod.yml"), "shop:\n  tax-rate: 0.19\n");

        try (var server = new SpringApplication(ConfigServerApplication.class).run(
                "--server.port=0", "--spring.profiles.active=native",
                "--spring.cloud.config.server.native.search-locations=file:" + repo + "/",
                "--spring.main.banner-mode=off", "--logging.level.root=WARN")) {
            int serverPort = ((WebServerApplicationContext) server).getWebServer().getPort();

            try (var orders = new SpringApplication(OrdersApplication.class).run(
                    "--spring.application.name=orders", "--spring.profiles.active=prod",
                    "--spring.config.import=configserver:http://localhost:" + serverPort,
                    // the server jar switches the client off in its own JVM; switch it on
                    "--spring.cloud.config.enabled=true",
                    "--server.port=0", "--management.endpoints.web.exposure.include=refresh",
                    "--spring.main.banner-mode=off", "--logging.level.root=WARN")) {
                System.out.println("orders started with configuration from the server:");
                print(orders);

                Files.writeString(repo.resolve("orders-prod.yml"), "shop:\n  tax-rate: 0.17\n");
                System.out.println("orders-prod.yml changed to 0.17, nothing refreshed yet:");
                print(orders);

                int port = ((WebServerApplicationContext) orders).getWebServer().getPort();
                HttpResponse<String> response = HttpClient.newHttpClient().send(
                        HttpRequest.newBuilder(URI.create(
                                "http://localhost:" + port + "/actuator/refresh"))
                                .POST(HttpRequest.BodyPublishers.noBody()).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("POST /actuator/refresh -> " + response.statusCode()
                        + " " + response.body());
                print(orders);
            }
        }
    }

    static void print(ConfigurableApplicationContext context) {
        System.out.println("  Environment               "
                + context.getEnvironment().getProperty("shop.tax-rate"));
        System.out.println("  ShopSettings (setters)    "
                + context.getBean(ShopSettings.class).getTaxRate());
        System.out.println("  ShopRecord (constructor)  "
                + context.getBean(ShopRecord.class).taxRate());
        System.out.println("  @RefreshScope @Value      "
                + context.getBean(TaxCalculator.class).taxRate());
        System.out.println("  plain singleton @Value    "
                + context.getBean(PlainCalculator.class).taxRate());
    }
}
Output
orders started with configuration from the server:
  Environment               0.19
  ShopSettings (setters)    0.19
  ShopRecord (constructor)  0.19
  @RefreshScope @Value      0.19
  plain singleton @Value    0.19
orders-prod.yml changed to 0.17, nothing refreshed yet:
  Environment               0.19
  ShopSettings (setters)    0.19
  ShopRecord (constructor)  0.19
  @RefreshScope @Value      0.19
  plain singleton @Value    0.19
POST /actuator/refresh -> 200 ["shop.tax-rate"]
  Environment               0.17
  ShopSettings (setters)    0.17
  ShopRecord (constructor)  0.19
  @RefreshScope @Value      0.17
  plain singleton @Value    0.19
  • At start-up every bean had 0.19, the value from orders-prod.yml, which took precedence over 0.21 in application.yml. The client found the server through spring.config.import=configserver:... and sent its name and profile from spring.application.name and spring.profiles.active.
  • After the file changed to 0.17, nothing changed in the service, not even the Environment. A client reads from the server only at start-up and on refresh; the server is not watched or polled.
  • POST /actuator/refresh returned the list of keys that changed, ["shop.tax-rate"]. The client fetched its configuration again and the Environment now answered 0.17.
  • ShopSettings, which has setters, was rebound in place and showed 0.17. The ShopRecord record, bound through its constructor, kept 0.19.
  • The @RefreshScope bean was created again on its next use and read 0.17. The plain singleton with the same @Value field kept 0.19, just like the beans in the last program on this page.

The line with spring.cloud.config.enabled=true is needed only because the server and the client share one JVM here. The server jar adds a default of spring.cloud.config.enabled=false to every application that has it on the classpath, so that a server does not try to fetch configuration from itself. A separate client service, with only spring-cloud-starter-config, does not need the line. The refresh endpoint is part of Spring Cloud Context and needs Spring Boot Actuator, and like every actuator endpoint except health it must be exposed explicitly. A client for real use has this application.yml:

YAML
# dependency: spring-cloud-starter-config
spring:
  application:
    name: orders                      # the {application} part of the request
  profiles:
    active: prod                      # the {profile} part
  config:
    import: "configserver:http://config.internal:8888"
  cloud:
    config:
      fail-fast: true                 # as without optional: do not start without it
      label: main                     # the Git branch to read
  • Without a URL, configserver: uses http://localhost:8888. The URL in the import takes precedence over spring.cloud.config.uri.
  • optional:configserver: lets the service start without the server. That is convenient in development and dangerous in production, where a service may then run on its built-in defaults.
  • With spring-retry and the AspectJ starter on the classpath and fail-fast: true, the client retries the connection before giving up: by default 6 attempts, starting 1 second apart with a multiplier of 1.1. Retry settings can also go in the import URL, such as configserver:http://config.internal:8888?max-attempts=10.
  • The remote properties are placed in the Environment like any imported file. As in the first program, sources higher in the list, such as command-line arguments and environment variables, can still override them.

Since Spring Cloud 2020.0, the old bootstrap.yml is not needed for this; the import replaces it. Applications that still have spring-cloud-starter-bootstrap on the classpath can usually remove it when they switch to spring.config.import.

Refreshing configuration at run time

Changing a value in Git does not change a running service by itself. The new value must reach the Environment, and then the beans that already read the old value must read it again. This program simulates the first step by adding a property source with a new tax rate, the way a refresh does, and checks what the application sees:

Java
package demo.config.stale;

import java.math.BigDecimal;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

public class StaleProperties {

    @ConfigurationProperties("shop")
    record ShopProperties(BigDecimal taxRate, String currency) {
    }

    static class Checkout {
        @Value("${shop.tax-rate}")
        BigDecimal taxRate;
    }

    @SpringBootConfiguration
    @EnableConfigurationProperties(ShopProperties.class)
    static class ShopApplication {
        @Bean
        Checkout checkout() {
            return new Checkout();
        }
    }

    public static void main(String[] args) {
        try (var context = new SpringApplication(ShopApplication.class).run(
                "--spring.main.banner-mode=off", "--logging.level.root=OFF",
                "--spring.main.web-application-type=none",
                "--shop.tax-rate=0.21", "--shop.currency=EUR")) {
            ConfigurableEnvironment env = context.getEnvironment();
            System.out.println("At start-up:");
            print(context.getBean(ShopProperties.class), context.getBean(Checkout.class), env);

            // what a config server delivers on refresh: a new value in the Environment
            env.getPropertySources().addFirst(new MapPropertySource("refreshed",
                    Map.of("shop.tax-rate", "0.25")));
            System.out.println("After the Environment changed:");
            print(context.getBean(ShopProperties.class), context.getBean(Checkout.class), env);

            // what a refresh must do: bind the properties again
            ShopProperties rebound = Binder.get(env).bind("shop", ShopProperties.class).get();
            System.out.println("Bound again from the Environment: " + rebound);
        }
    }

    static void print(ShopProperties props, Checkout checkout, ConfigurableEnvironment env) {
        System.out.println("  Environment     shop.tax-rate = " + env.getProperty("shop.tax-rate"));
        System.out.println("  @ConfigurationProperties bean = " + props.taxRate());
        System.out.println("  @Value field                  = " + checkout.taxRate);
    }
}
Output
At start-up:
  Environment     shop.tax-rate = 0.21
  @ConfigurationProperties bean = 0.21
  @Value field                  = 0.21
After the Environment changed:
  Environment     shop.tax-rate = 0.25
  @ConfigurationProperties bean = 0.21
  @Value field                  = 0.21
Bound again from the Environment: ShopProperties[taxRate=0.25, currency=EUR]
  • At start-up, the Environment, the @ConfigurationProperties record and the @Value field all had 0.21.
  • After the new source was added, the Environment answered 0.25, but both beans still held 0.21. A bean reads configuration when it is created and never again.
  • Binding shop again from the Environment with Binder produced a new ShopProperties with 0.25. Refreshing means doing exactly that for the affected beans.

Spring Cloud automates both steps, as the client program above showed. A POST to /actuator/refresh, from Spring Cloud Context, fetches the configuration again, updates the Environment and publishes an EnvironmentChangeEvent. Mutable @ConfigurationProperties beans, with setters, are then rebound in place, as ShopSettings was. Immutable ones, such as the records in both programs, are bound through the constructor and are not rebound, so prefer setters for properties that must refresh. Beans annotated with @RefreshScope, which suits beans that use @Value or build clients from configuration, are recreated the next time they are used:

Java
@RefreshScope
@Component
public class TaxCalculator {
    @Value("${shop.tax-rate}")
    private BigDecimal taxRate;        // read again after each refresh
}

Spring Cloud Bus sends the refresh to every instance at once, over RabbitMQ or Kafka, through /actuator/busrefresh; Bus needs a message broker and was not run here. Not everything can be refreshed safely: a connection pool, a server port or a bean that copied the value into another object keeps the old setting. Many teams therefore restart services for configuration changes, with a rolling deployment, and keep run-time refresh for a few switches such as feature flags and log levels.

Traps with external configuration

  • Silent fallbacks: an optional: import that fails, or a typo in a property name, leaves the default in place without an error. Bind settings to @ConfigurationProperties classes with @Validated constraints, so that a missing value stops the start-up.
  • Unexpected precedence: an environment variable such as SHOP_TAX_RATE left on a host overrides every file and the config server. When a value is not what you expect, the /actuator/env endpoint shows which source supplied it.
  • Secrets in plain text: a secret in a Git repository stays in its history forever. Store it encrypted with {cipher}, or keep it in a secrets manager and import it from there.
  • A single point of failure: services that cannot start without the config server cannot start during its outage either. Run several instances behind a load balancer, and remember that running services are unaffected, since they read configuration only at start-up and on refresh.
  • Refreshed values that do not apply: as the last program shows, only rebound or recreated beans see a new value. Test a refresh of each setting you intend to change at run time.

Choosing a configuration approach

Configuration approaches for common situations
SituationApproach
A few services, settings per environmentapplication-{profile}.yml and environment variables
Settings in files outside the jarspring.config.import=file:..., optional: only when truly optional
Running on KubernetesConfigMaps and Secrets mounted and imported with configtree:
Many services with shared, reviewed configurationSpring Cloud Config Server with a Git backend
Secrets with rotation and access controlVault or a cloud secrets manager, imported directly
Changing a few values without a restart/actuator/refresh with @ConfigurationProperties or @RefreshScope
Changing values on every instance at onceSpring Cloud Bus, or a rolling restart

Whatever the source, the properties end up in the same Environment with the same precedence rules, so the binding and testing techniques do not change. For how properties are bound and validated, see application properties, and for profiles, Spring profiles.