Spring Boot profiles: one application, several environments
Profiles let one Spring Boot application load different settings and beans in development, test and production. This page runs profile-specific files, @Profile expressions, groups and multi-document files, and shows the mistakes that start without an error but leave the application with the wrong beans.
Contents
What a profile is
An application usually runs in several places: on a laptop, in a test pipeline, and in production. Most of the code is the same everywhere, but some settings and some beans are not. Production talks to PostgreSQL and a real mail server; a laptop uses an in-memory H2 database and prints emails to the console.
A profile is a name, such as devprodEnvironment
- Configuration files: for each active profile, Spring Boot also loads
(orapplication-{profile}.properties ), and any document inside a file marked with.yaml . Their values override the plainspring.config.activate.on-profile .application.properties - Beans: a
,@Component class or@Configuration method annotated with@Bean is registered only when its profile expression matches.@Profile
When no profile is active, Spring treats a profile named default
| Mechanism | Example | Best for |
|---|---|---|
| Environment variable | SPRING_PROFILES_ACTIVE=prod | Containers, Kubernetes, cloud platforms |
| Command-line argument | java -jar app.jar --spring.profiles.active=prod | Manual runs and scripts |
| System property | java -Dspring.profiles.active=prod -jar app.jar | JVM launch scripts |
application.properties | spring.profiles.active=dev | A default for local work; overridden by any of the above |
| Code | SpringApplication.setAdditionalProfiles("eu") | Profiles every run of this launcher needs |
| Tests | @ActiveProfiles("test") | Spring test contexts |
Profiles are resolved early, while Spring Boot is still building the Environment
The programs on this page run Spring Boot 4.1.2 without a web server. Each one writes its configuration files into a temporary folder and puts that folder on the classpath, where Spring Boot finds the files as it would in src/main/resources
Profile-specific files
One base file and three profile files, run four times with different active profiles, show how the values stack. The base file sets three keys, and each profile file overrides some of them:
package profiles.files;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
@SpringBootApplication
public class ProfileFiles {
static ClassLoader resources;
static void run(String... args) {
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
ProfileFiles.class);
try (var context = app.run(args)) {
Environment env = context.getEnvironment();
System.out.println("args " + Arrays.toString(args));
System.out.println(" active profiles: " + Arrays.toString(env.getActiveProfiles())
+ ", default profiles: " + Arrays.toString(env.getDefaultProfiles()));
System.out.println(" db.url = " + env.getProperty("db.url"));
System.out.println(" db.pool = " + env.getProperty("db.pool"));
System.out.println(" mail.mode = " + env.getProperty("mail.mode"));
}
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
db.url=jdbc:h2:mem:local
db.pool=5
mail.mode=log-only
""");
Files.writeString(dir.resolve("application-default.properties"), """
db.pool=2
""");
Files.writeString(dir.resolve("application-dev.properties"), """
db.url=jdbc:h2:mem:dev
""");
Files.writeString(dir.resolve("application-prod.properties"), """
db.url=jdbc:postgresql://db.internal:5432/shop
db.pool=50
mail.mode=smtp
""");
resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
ProfileFiles.class.getClassLoader());
run();
run("--spring.profiles.active=dev");
run("--spring.profiles.active=prod");
run("--spring.profiles.active=prod,dev");
}
}
args []
active profiles: [], default profiles: [default]
db.url = jdbc:h2:mem:local
db.pool = 2
mail.mode = log-only
args [--spring.profiles.active=dev]
active profiles: [dev], default profiles: [default]
db.url = jdbc:h2:mem:dev
db.pool = 5
mail.mode = log-only
args [--spring.profiles.active=prod]
active profiles: [prod], default profiles: [default]
db.url = jdbc:postgresql://db.internal:5432/shop
db.pool = 50
mail.mode = smtp
args [--spring.profiles.active=prod,dev]
active profiles: [prod, dev], default profiles: [default]
db.url = jdbc:h2:mem:dev
db.pool = 50
mail.mode = smtp
- With no active profile, the
profile applied, sodefault loaded and changedapplication-default.properties from 5 to 2. The other two values came from the base file.db.pool - With
, onlydev changed. Keys missing fromdb.url kept their base values, andapplication-dev.properties was back to 5, because thedb.pool profile was no longer active.default - With
, all three keys came fromprod .application-prod.properties - With
, both files loaded and the later profile won where they overlap:prod,dev is dev's H2 URL, whiledb.url anddb.pool , which only prod sets, kept prod's values.mail.mode
A profile file only needs the keys that differ. Keep everything shared in application.properties
@Profile on beans
Settings are not always enough: sometimes production needs a different class altogether. A notifier and a payment gateway with several implementations show the expression forms @Profile
package profiles.beans;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class ProfileBeans {
interface Notifier {
String describe();
}
@Component
@Profile("prod")
static class SmtpNotifier implements Notifier {
public String describe() {
return "sends real email";
}
}
@Component
@Profile("!prod")
static class ConsoleNotifier implements Notifier {
public String describe() {
return "prints email to the console";
}
}
interface PaymentGateway {
}
@Configuration
static class PaymentConfig {
@Bean
@Profile("default")
PaymentGateway stubGateway() {
return new PaymentGateway() { };
}
@Bean
@Profile({"dev", "test"})
PaymentGateway sandboxGateway() {
return new PaymentGateway() { };
}
@Bean
@Profile("prod & eu")
PaymentGateway euGateway() {
return new PaymentGateway() { };
}
@Bean
@Profile("prod & !eu")
PaymentGateway usGateway() {
return new PaymentGateway() { };
}
}
static void run(String profiles) {
SpringApplication app = new SpringApplication(ProfileBeans.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
String[] args = profiles.isEmpty()
? new String[0] : new String[] {"--spring.profiles.active=" + profiles};
try (var context = app.run(args)) {
System.out.println("active " + Arrays.toString(
context.getEnvironment().getActiveProfiles()));
var notifiers = new TreeMap<>(context.getBeansOfType(Notifier.class));
notifiers.forEach((name, bean) -> System.out.println(
" Notifier: " + bean.getClass().getSimpleName()
+ " (" + bean.describe() + ")"));
System.out.println(" PaymentGateway: "
+ Arrays.toString(context.getBeanNamesForType(PaymentGateway.class)));
}
}
public static void main(String[] args) {
run("");
run("dev");
run("prod,eu");
run("prod");
}
}
active []
Notifier: ConsoleNotifier (prints email to the console)
PaymentGateway: [stubGateway]
active [dev]
Notifier: ConsoleNotifier (prints email to the console)
PaymentGateway: [sandboxGateway]
active [prod, eu]
Notifier: SmtpNotifier (sends real email)
PaymentGateway: [euGateway]
active [prod]
Notifier: SmtpNotifier (sends real email)
PaymentGateway: [usGateway]
registered@Profile("!prod") in every run withoutConsoleNotifier , including the run with no profile at all.prod- With no profile active, only
, markedstubGateway , existed. With@Profile("default") it was gone, replaced bydev , becausesandboxGateway matches either name.{"dev", "test"} matchedprod,eu and produced"prod & eu" .euGateway alone matchedprod and produced"prod & !eu" .usGateway- In every run exactly one
existed, so code that injects one never saw two candidates or none.PaymentGateway
Expressions support !&|&|"prod & (eu | uk)"@Configuration@Profile@Bean
Groups, includes and multi-document files
Real environments often combine several concerns: a production database, a production message broker and metrics export. Profile groups give such a combination one name. This program activates the group production
package profiles.groups;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
@SpringBootApplication
public class ProfileGroups {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("config");
Files.writeString(dir.resolve("application.properties"), """
spring.main.banner-mode=off
logging.level.root=WARN
spring.profiles.include=metrics
spring.profiles.group.production=proddb,prodmq
db.url=jdbc:h2:mem:local
mq.host=localhost
metrics.export=none
#---
spring.config.activate.on-profile=proddb
db.url=jdbc:postgresql://db.internal:5432/shop
#---
spring.config.activate.on-profile=prodmq
mq.host=mq.internal
#---
spring.config.activate.on-profile=metrics
metrics.export=otlp
#---
spring.config.activate.on-profile=production & !debug
log.sql=false
""");
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
ProfileGroups.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
ProfileGroups.class);
app.setAdditionalProfiles("eu");
try (var context = app.run("--spring.profiles.active=production")) {
Environment env = context.getEnvironment();
System.out.println("active profiles: " + Arrays.toString(env.getActiveProfiles()));
System.out.println("db.url = " + env.getProperty("db.url"));
System.out.println("mq.host = " + env.getProperty("mq.host"));
System.out.println("metrics.export = " + env.getProperty("metrics.export"));
System.out.println("log.sql = " + env.getProperty("log.sql"));
System.out.println("matchesProfiles(\"production & eu\"): "
+ env.matchesProfiles("production & eu"));
System.out.println("matchesProfiles(\"proddb\"): "
+ env.matchesProfiles("proddb"));
System.out.println("matchesProfiles(\"dev | test\"): "
+ env.matchesProfiles("dev | test"));
}
}
}
active profiles: [eu, metrics, production, proddb, prodmq]
db.url = jdbc:postgresql://db.internal:5432/shop
mq.host = mq.internal
metrics.export = otlp
log.sql = false
matchesProfiles("production & eu"): true
matchesProfiles("proddb"): true
matchesProfiles("dev | test"): false
- Activating
also activatedproduction andproddb , fromprodmq . The group members appear right after the group in the list.spring.profiles.group.production=proddb,prodmq is active in every run because ofmetrics , andspring.profiles.include=metrics because the code calledeu . Both come before the profiles fromsetAdditionalProfiles("eu") , so those take precedence over them.spring.profiles.active- Each
line starts a new document in the same file. A document with#--- applies only when that profile is active, sospring.config.activate.on-profile ,db.url andmq.host all took their production values.metrics.export - The last document used an expression,
, and applied becauseproduction & !debug was not active.debug evaluates the same expressions in code. It returnedEnvironment.matchesProfiles fortrue , which was activated only through the group.proddb
In YAML the separator is ---spring.config.activate.on-profilespring.profilesspring.config.activate.on-cloud-platformkubernetes
Traps: misspelt names, the vanishing default and invalid places
Profile mistakes are easy to make and some of them fail silently. This program runs four of them against beans for defaultlocalprod
package profiles.traps;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.DefaultResourceLoader;
@SpringBootApplication
public class ProfileTraps {
interface PaymentGateway {
}
@Configuration
static class PaymentConfig {
@Bean
@Profile("default")
PaymentGateway stubGateway() {
return new PaymentGateway() { };
}
@Bean
@Profile("local")
PaymentGateway localGateway() {
return new PaymentGateway() { };
}
@Bean
@Profile("prod")
PaymentGateway realGateway() {
return new PaymentGateway() { };
}
}
static Path dir;
static void run(String label, String... args) throws Exception {
System.out.println(label);
var resources = new URLClassLoader(new URL[] {dir.toUri().toURL()},
ProfileTraps.class.getClassLoader());
SpringApplication app = new SpringApplication(new DefaultResourceLoader(resources),
ProfileTraps.class);
try (var context = app.run(args)) {
System.out.println(" active " + Arrays.toString(
context.getEnvironment().getActiveProfiles()) + ", default "
+ Arrays.toString(context.getEnvironment().getDefaultProfiles())
+ ", gateways " + Arrays.toString(
context.getBeanNamesForType(PaymentGateway.class)));
} catch (RuntimeException e) {
System.out.println(" startup failed: " + e.getClass().getSimpleName());
System.out.println(" " + e.getMessage());
}
}
public static void main(String[] args) throws Exception {
dir = Files.createTempDirectory("config");
String base = """
spring.main.banner-mode=off
logging.level.root=OFF
""";
Files.writeString(dir.resolve("application.properties"), base);
Files.writeString(dir.resolve("application-dev.properties"), """
spring.profiles.active=local
""");
run("1. A misspelt profile name, prd instead of prod:",
"--spring.profiles.active=prd");
run("2. spring.profiles.default=local, no active profile:",
"--spring.profiles.default=local");
run("3. spring.profiles.active inside application-dev.properties:",
"--spring.profiles.active=dev");
Files.writeString(dir.resolve("application.properties"), base + """
#---
spring.profiles=prod
pay.url=https://pay.example.com
""");
run("4. The pre-2.4 key spring.profiles in application.properties:");
}
}
1. A misspelt profile name, prd instead of prod:
active [prd], default [default], gateways []
2. spring.profiles.default=local, no active profile:
active [], default [local], gateways [localGateway]
3. spring.profiles.active inside application-dev.properties:
startup failed: InvalidConfigDataPropertyException
Property 'spring.profiles.active' imported from location 'class path resource [application-dev.properties]' is invalid in a profile specific resource [origin: class path resource [application-dev.properties] - 1:24]
4. The pre-2.4 key spring.profiles in application.properties:
startup failed: InvalidConfigDataPropertyException
Property 'spring.profiles' imported from location 'class path resource [application.properties]' is invalid and should be replaced with 'spring.config.activate.on-profile' [origin: class path resource [application.properties] - 4:17]
- Misspelt profile:
started without any warning. Theprd bean was not created, and theprod stub was not either, because a profile was active. The application ended up with no gateway at all, and would fail only when something injects one.default - Changing the default:
renamed the fallback profile. With nothing active,spring.profiles.default=local applied andlocal was created, while thelocalGateway bean was not.@Profile("default") - Activating from a profile file:
insidespring.profiles.active stopped startup withapplication-dev.properties . A profile-specific file cannot activate more profiles, because the set of profiles must be known before those files are read. Use a group instead.InvalidConfigDataPropertyException - The old document key:
, the way documents were tied to a profile before Spring Boot 2.4, also stopped startup. The message names the replacement,spring.profiles=prod , and the exact line and column.spring.config.activate.on-profile
Two more problems appear in larger code bases. Using profiles for feature flags (@Profile("new-checkout")@ConditionalOnPropertyINFOThe following 1 profile is active: "prd"No active profile set, falling back to 1 default profile: "local"env
Profiles in tests
A Spring test context starts with no active profile, so the default@ActiveProfiles
@SpringBootTest
@ActiveProfiles("test")
class CheckoutServiceTest {
// application-test.properties is loaded and @Profile("test") beans exist
}
Each distinct set of active profiles creates a separate application context, which the test framework caches by configuration. Ten test classes with ten different profile combinations start ten contexts, so keep the combinations few. For a single changed value, @SpringBootTest(properties = "key=value")@TestPropertySource
Choosing between profiles and other options
| Need | Use |
|---|---|
| A few settings differ per environment | application-{profile}.properties |
| A different implementation per environment | @Profile |
| Several concerns switched on together | spring.profiles.group.<name> |
| A profile every run needs | spring.profiles.includesetAdditionalProfiles |
| A fallback for running with no setup | The defaultspring.profiles.default |
| Turning one feature on or off | A property with @ConditionalOnProperty |
| Secrets per environment | Environment variables or a secret store import, not a committed application-prod.properties |
Profiles decide which configuration is loaded. How each value is then read and bound is covered on the @Profile