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 dev or prod, that switches on a set of configuration and beans. At startup the Environment holds a list of active profiles, and two things react to it:

  • Configuration files: for each active profile, Spring Boot also loads application-{profile}.properties (or .yaml), and any document inside a file marked with spring.config.activate.on-profile. Their values override the plain application.properties.
  • Beans: a @Component, @Configuration class or @Bean method annotated with @Profile is registered only when its profile expression matches.

When no profile is active, Spring treats a profile named default as active instead. That gives a fallback for running with no setup at all, and it disappears as soon as any profile is activated. Profiles are activated in several ways:

Ways to activate profiles
MechanismExampleBest for
Environment variableSPRING_PROFILES_ACTIVE=prodContainers, Kubernetes, cloud platforms
Command-line argumentjava -jar app.jar --spring.profiles.active=prodManual runs and scripts
System propertyjava -Dspring.profiles.active=prod -jar app.jarJVM launch scripts
application.propertiesspring.profiles.active=devA default for local work; overridden by any of the above
CodeSpringApplication.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 and before any bean is created. It first reads the files that are not tied to a profile, works out the active profiles from them and from the sources above, and only then loads the profile-specific files. That order explains two rules shown later: a profile file cannot activate further profiles, and a bean cannot decide which profiles are active.

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:

Java
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");
    }
}
Output
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 default profile applied, so application-default.properties loaded and changed db.pool from 5 to 2. The other two values came from the base file.
  • With dev, only db.url changed. Keys missing from application-dev.properties kept their base values, and db.pool was back to 5, because the default profile was no longer active.
  • With prod, all three keys came from application-prod.properties.
  • With prod,dev, both files loaded and the later profile won where they overlap: db.url is dev's H2 URL, while db.pool and mail.mode, which only prod sets, kept prod's values.

A profile file only needs the keys that differ. Keep everything shared in application.properties, so that a reader can see what changes per environment by reading the small files. Profile files outside the jar override those inside it, which lets an operator adjust one environment without rebuilding.

@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 accepts:

Java
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");
    }
}
Output
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]
  • @Profile("!prod") registered ConsoleNotifier in every run without prod, including the run with no profile at all.
  • With no profile active, only stubGateway, marked @Profile("default"), existed. With dev it was gone, replaced by sandboxGateway, because {"dev", "test"} matches either name.
  • prod,eu matched "prod & eu" and produced euGateway. prod alone matched "prod & !eu" and produced usGateway.
  • In every run exactly one PaymentGateway existed, so code that injects one never saw two candidates or none.

Expressions support ! (not), & (and), | (or) and parentheses; mixing & and | needs parentheses, as in "prod & (eu | uk)". On a @Configuration class, @Profile switches all of its @Bean methods on or off together.

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 and keeps all profile-specific settings in a single file:

Java
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"));
        }
    }
}
Output
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 production also activated proddb and prodmq, from spring.profiles.group.production=proddb,prodmq. The group members appear right after the group in the list.
  • metrics is active in every run because of spring.profiles.include=metrics, and eu because the code called setAdditionalProfiles("eu"). Both come before the profiles from spring.profiles.active, so those take precedence over them.
  • Each #--- line starts a new document in the same file. A document with spring.config.activate.on-profile applies only when that profile is active, so db.url, mq.host and metrics.export all took their production values.
  • The last document used an expression, production & !debug, and applied because debug was not active.
  • Environment.matchesProfiles evaluates the same expressions in code. It returned true for proddb, which was activated only through the group.

In YAML the separator is ---. spring.config.activate.on-profile replaced the older spring.profiles document key in Spring Boot 2.4; the traps section shows what happens to configuration that still uses the old key. A document can also carry spring.config.activate.on-cloud-platform, for example kubernetes, to apply only on that platform whatever the profiles are.

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 default, local and prod:

Java
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:");
    }
}
Output
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: prd started without any warning. The prod bean was not created, and the default 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.
  • Changing the default: spring.profiles.default=local renamed the fallback profile. With nothing active, local applied and localGateway was created, while the @Profile("default") bean was not.
  • Activating from a profile file: spring.profiles.active inside application-dev.properties stopped startup with InvalidConfigDataPropertyException. 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.
  • The old document key: spring.profiles=prod, the way documents were tied to a profile before Spring Boot 2.4, also stopped startup. The message names the replacement, spring.config.activate.on-profile, and the exact line and column.

Two more problems appear in larger code bases. Using profiles for feature flags (@Profile("new-checkout")) mixes environment and behaviour; a property with @ConditionalOnProperty or a feature flag service is clearer. And many fine-grained profiles make it hard to know what a running instance contains. Spring Boot logs the result at startup, at INFO level, as The following 1 profile is active: "prd" or No active profile set, falling back to 1 default profile: "local" for the first two runs above, and the actuator env endpoint lists the active profiles too. Checking that line is the quickest way to catch a misspelt name.

Profiles in tests

A Spring test context starts with no active profile, so the default beans and files apply unless the test chooses otherwise. @ActiveProfiles picks the profiles for one test class:

Java
@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") or @TestPropertySource is lighter than a new profile. This snippet is not run on this page; the Spring Boot testing page covers test contexts.

Choosing between profiles and other options

When to use a profile and when to use something else
NeedUse
A few settings differ per environmentapplication-{profile}.properties, or environment variables set by the platform
A different implementation per environment@Profile on the bean or its configuration class
Several concerns switched on togetherspring.profiles.group.<name>
A profile every run needsspring.profiles.include or setAdditionalProfiles
A fallback for running with no setupThe default profile, or spring.profiles.default
Turning one feature on or offA property with @ConditionalOnProperty, not a profile
Secrets per environmentEnvironment 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 configuration properties page, and the bean scopes and Java configuration pages explain the bean definitions that @Profile switches on and off.