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 Environmentapplication.yml@Value@ConfigurationProperties
With one service, application.ymlspring.config.import
| Source | Import or mechanism | Best for |
|---|---|---|
| Files next to the jar or in a mounted volume | file:optional:file: | Settings per environment, deployed with the application |
| One file per key, as Kubernetes mounts Secrets | configtree: | Secrets and ConfigMaps on Kubernetes |
| Environment variables | Built in, relaxed binding (SHOP_TAX_RATE | A few values per deployment, containers |
| Spring Cloud Config Server | configserver: | Central, versioned configuration for many services, from Git |
| HashiCorp Vault, AWS Parameter Store or Secrets Manager | vault://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-serverspring-boot-starter-actuator
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:
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>"));
}
}
}
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]
came fromshop.currency , the only source that defines it.shared.yml is 0.19, not 0.21: both files define it, and of several imports, the later one wins. The list of sources shows why:shop.tax-rate sits aboveeu-override.properties .shared.yml came from the command line, which is near the top of the list, above every imported file.shop.support-email ,cachedrandom andconfigServerClient 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 aspringCloudClientHostInfo key, so they change nothing here.shop- The
import ofoptional: was silently skipped. The same import withoutnot-there.yml stopped the application withoptional: .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:
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:echo
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));
}
}
}
}
db.username = [shop_app]
db.password = [s3cr3t]
payment.api-key = [pk_live_123]
- The file
became the propertydb/username : directory levels become the dots of the property name.db.username - The file name
, which already contains a dot, becamepayment.api-key as well, so both layouts work.payment.api-key isdb.password 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.s3cr3t
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 nativeorders
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();
}
}
}
}
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
has the formGET /orders/prod , with an optional/{application}/{profile} for a Git branch, tag or commit. The answer listed three files:/{label} ,orders-prod.yml andorders.yml , most specific first.application.yml - The server does not merge the files: it returns each one as a separate property source and leaves the merging to the client.
appears twice, as 0.19 and 0.21, and the client takes the first one, 0.19.shop.tax-rate - With the
profile,default dropped out and only two sources remained.orders-prod.yml appears in both answers, because it holds what every service shares.application.yml andlabel areversion because a plain directory has no branches or commits. With the Git backend,null holds the commit id, so a client can log exactly which revision of its configuration it runs with.version returned the same configuration already merged into one YAML document, withGET /orders-prod.yml 0.19. The server also offerstax-rate and.properties , which suits scripts and non-Spring clients..json
The program prints repo/application.ymlspring-cloud-config-server@EnableConfigServer
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
are stored encrypted in Git and decrypted by the server with the key in{cipher} or a key store.encrypt.key
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 ordersprodorders-prod.yml
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());
}
}
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
, which took precedence over 0.21 inorders-prod.yml . The client found the server throughapplication.yml and sent its name and profile fromspring.config.import=configserver:... andspring.application.name .spring.profiles.active - After the file changed to 0.17, nothing changed in the service, not even the
. A client reads from the server only at start-up and on refresh; the server is not watched or polled.Environment returned the list of keys that changed,POST /actuator/refresh . The client fetched its configuration again and the["shop.tax-rate"] now answered 0.17.Environment , which has setters, was rebound in place and showed 0.17. TheShopSettings record, bound through its constructor, kept 0.19.ShopRecord- The
bean was created again on its next use and read 0.17. The plain singleton with the same@RefreshScope field kept 0.19, just like the beans in the last program on this page.@Value
The line with spring.cloud.config.enabled=truespring.cloud.config.enabled=falsespring-cloud-starter-confighealthapplication.yml
# 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,
usesconfigserver: . The URL in the import takes precedence overhttp://localhost:8888 .spring.cloud.config.uri 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.optional:configserver:- With
and the AspectJ starter on the classpath andspring-retry , 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 asfail-fast: true .configserver:http://config.internal:8888?max-attempts=10 - The remote properties are placed in the
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.Environment
Since Spring Cloud 2020.0, the old bootstrap.ymlspring-cloud-starter-bootstrapspring.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
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);
}
}
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
, theEnvironment record and the@ConfigurationProperties field all had 0.21.@Value - After the new source was added, the
answered 0.25, but both beans still held 0.21. A bean reads configuration when it is created and never again.Environment - Binding
again from theshop withEnvironment produced a newBinder with 0.25. Refreshing means doing exactly that for the affected beans.ShopProperties
Spring Cloud automates both steps, as the client program above showed. A POST/actuator/refreshEnvironmentEnvironmentChangeEvent@ConfigurationPropertiesShopSettings@RefreshScope@Value
@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
Traps with external configuration
- Silent fallbacks: an
import that fails, or a typo in a property name, leaves the default in place without an error. Bind settings tooptional: classes with@ConfigurationProperties constraints, so that a missing value stops the start-up.@Validated - Unexpected precedence: an environment variable such as
left on a host overrides every file and the config server. When a value is not what you expect, theSHOP_TAX_RATE endpoint shows which source supplied it./actuator/env - Secrets in plain text: a secret in a Git repository stays in its history forever. Store it encrypted with
, or keep it in a secrets manager and import it from there.{cipher} - 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
| Situation | Approach |
|---|---|
| A few services, settings per environment | application-{profile}.yml |
| Settings in files outside the jar | spring.config.import=file:...optional: |
| Running on Kubernetes | ConfigMaps and Secrets mounted and imported with configtree: |
| Many services with shared, reviewed configuration | Spring Cloud Config Server with a Git backend |
| Secrets with rotation and access control | Vault or a cloud secrets manager, imported directly |
| Changing a few values without a restart | /actuator/refresh@ConfigurationProperties@RefreshScope |
| Changing values on every instance at once | Spring Cloud Bus, or a rolling restart |
Whatever the source, the properties end up in the same Environment