Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 66 ยท Auto-Configuration and Configuration

Profiles and Environment-Specific Config

Use Spring Boot profiles to change configuration and beans per environment: activation, profile files, groups, @Profile expressions, config import and secrets handling.

An application behaves differently depending on where it runs. On your laptop it uses an in-memory database and verbose logs. In production it talks to a managed database, logs in a structured format and sends real email. Spring Boot's tool for this is the profile: a named label such as dev, test or prod that switches configuration files and beans on or off.

Profiles are easy to start with and easy to misuse. This lesson shows how to activate them, how profile-specific configuration layers on top of the base settings, how to group profiles, how to include external files with spring.config.import, and where secrets belong. Spring Boot code and files are read-only here, with runnable stand-ins for profile resolution and for @Profile expressions.

Activating profiles

If you do nothing, the application runs with the profile named default. To activate others, set spring.profiles.active to a comma-separated list, using any property source:

Terminal
# command line (strongest)
java -jar shop.jar --spring.profiles.active=prod

# environment variable (typical for containers)
SPRING_PROFILES_ACTIVE=prod,eu java -jar shop.jar

# JVM system property
java -Dspring.profiles.active=dev -jar shop.jar

In tests, @ActiveProfiles("test") on the test class does the job. You can also add profiles on top of the active ones with spring.profiles.include, useful for a profile that always needs a companion.

What a profile controls

Config files application-prod.yml overrides application.yml.
Beans @Profile switches beans on or off.
Tests @ActiveProfiles picks the setup per test class.

Same jar, different behaviour.

1 / 2

Profile-specific files

Boot loads application.yml, then layers application-{profile}.yml for every active profile on top. Only the differences go into the profile file:

YAML
# application.yml (always loaded)
app:
  mail:
    host: localhost
    port: 1025
logging:
  level:
    root: INFO
YAML
# application-prod.yml (only when "prod" is active)
app:
  mail:
    host: smtp.example.com
    port: 587
logging:
  level:
    root: WARN

With prod active, app.mail.host is smtp.example.com and logging.level.root is WARN, while any key that only the base file defines (say server.port) stays as it was. If several profiles are active (prod,eu) and both set the same key, the profile listed last wins, so the order in spring.profiles.active matters.

You can also keep everything in one YAML file with multiple documents, each limited to a profile:

YAML
app:
  mail:
    host: localhost
---
spring:
  config:
    activate:
      on-profile: prod
app:
  mail:
    host: smtp.example.com

You cannot set spring.profiles.active or spring.profiles.include inside a document that is itself activated by on-profile. Boot rejects it, because a profile cannot decide which profiles are active. Activate profiles from the outside (command line, environment) or from a base document.

Profile groups

Real deployments tend to need several profiles at once: the database settings for production, the message broker settings for production, and so on. Instead of listing five names everywhere, define a group in your base file:

YAML
spring:
  profiles:
    group:
      prod:
        - proddb
        - prodmq
        - monitoring
      dev:
        - h2
        - debuglogs

Now --spring.profiles.active=prod activates prod, proddb, prodmq and monitoring, and Boot loads application-proddb.yml, application-prodmq.yml and so on. Operations only has to remember one name. Avoid depending on groups to override each other on the same key; give each profile its own area of settings and the order stops mattering.

The first TryIt models how the files layer. Each profile has its own map. The resolver expands groups into the full active list, applies the base file and then each profile in order, and records which file set each final value.

Java Resolving profile layers

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

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

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

What is real: the base file plus profile files layered in order, later profiles overriding earlier ones, groups expanding to several names, and missing profile files simply being skipped. What is the stand-in: Boot also merges lists and maps according to detailed rules, searches several locations for each file, and honours the full property source order from the previous lesson.

Beans per profile

@Profile makes a bean or whole configuration class conditional on the active profiles, a special case of the conditions you saw in Conditional Beans:

Java
public interface MailSender {
    void send(String to, String body);
}

@Service
@Profile("prod")
public class SmtpMailSender implements MailSender { /* real SMTP */ }

@Service
@Profile("!prod")
public class LoggingMailSender implements MailSender {
    public void send(String to, String body) {
        System.out.println("Would send to " + to + ": " + body);
    }
}

Exactly one MailSender exists in any environment, and nobody has to send real email from a laptop by mistake. Expressions use ! (not), & (and) and | (or), and Boot requires parentheses when you mix & and |:

Java
@Profile("cloud & !local")
@Profile("(dev | test) & !offline")

The second TryIt implements this tiny expression language with a recursive-descent parser, so you can see how the mixed-operator rule can be enforced: each parenthesis level may use & or |, never both.

Java Evaluating @Profile expressions

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

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

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

Real Spring also supports these expressions on @Profile and in environment.matchesProfiles(...), with the same refusal to guess operator precedence. The parser here is an imitation of the idea, not Spring's code.

Importing more configuration

spring.config.import pulls extra sources into the environment, which is how you keep secrets and shared settings outside the jar:

YAML
spring:
  config:
    import:
      - optional:file:./secrets.properties
      - optional:configtree:/run/secrets/

The optional: prefix means "do not fail if it is missing", so local development works without the file. configtree: reads a directory where each file name is a key and its content the value, exactly the layout that Kubernetes and Docker secrets produce. An import can also name another application file or a configuration server.

Secrets and the twelve-factor idea

The twelve-factor methodology says configuration that varies between deployments belongs in the environment, not in the code or the repository. For Boot this translates into rules you can apply today:

  • Commit only safe defaults. Never commit passwords, API keys or tokens, not even in application-prod.yml.
  • Deliver secrets through environment variables, mounted secret files (configtree:) or a secret manager, and reference them in files with placeholders such as password: ${DB_PASSWORD}.
  • Keep the set of profiles small and meaningful: environments (dev, test, prod) and infrastructure variants, not one profile per feature.
  • Build one artifact and promote it unchanged through environments. If a build differs per environment, you are not testing what you ship.
  • Be careful what endpoints and logs reveal; the Actuator env endpoint can show configuration, so it must be secured (see Actuator).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With application.yml setting logging.level.root=INFO and application-prod.yml setting it to WARN, what is the value when prod is active?

    Profile-specific files override the base file for the keys they define; all other keys keep their base values.
  2. 2. What does --spring.profiles.active=prod activate when spring.profiles.group.prod lists proddb and prodmq?

    A group lets one profile name activate several others, so operations pass a single name.
  3. 3. Which statement about secrets is the best advice?

    Secrets must stay out of the repository. Placeholders like ${DB_PASSWORD} read them from the environment at startup.
  4. 4. Why does @Profile("dev | test & cloud") fail in Spring?

    Spring requires explicit parentheses when & and | are combined, so the intent is never guessed.
  5. 5. Why avoid if (isProd) checks inside business code?

    Environment differences should live in configuration and swappable beans, so the same code path is tested in every environment.

Summary

  • Activate profiles with spring.profiles.active (command line, environment variable or JVM property); default applies when none is set.
  • application-{profile}.yml layers on top of the base file; with several profiles active, the last listed wins.
  • Profile groups activate several profiles under one name; on-profile documents live in one YAML file.
  • @Profile accepts !, & and |, with parentheses required when mixing & and |.
  • spring.config.import (with optional: and configtree:) brings in external files; secrets come from the environment, never from the repository.

Next: Logging.