Skip to main content
Configuration, profiles, conditions · Topic 3 of 5

Profiles

Definition​

A profile is a named set of beans or settings for one environment, such as dev or prod. A bean marked @Profile("dev") exists only when the dev profile is active, so one build can behave differently in each environment.

Example code​

A different bean for dev and prod

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

interface MailSender { String send(String to); }

@Configuration
class MailConfig {
@Bean @Profile("dev")
MailSender fakeSender() { return to -> "DEV: pretend email to " + to; } // never sends real mail

@Bean @Profile("prod")
MailSender realSender() { return to -> "PROD: real email to " + to; }
}

class Demo {
static void run(String profile) {
var context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles(profile); // in real apps: spring.profiles.active=dev
context.register(MailConfig.class);
context.refresh();
System.out.println(context.getBean(MailSender.class).send("asha@example.com"));
context.close();
}

public static void main(String[] args) {
run("dev");
run("prod");
}
}

// Output:
// DEV: pretend email to asha@example.com
// PROD: real email to asha@example.com

Finished this page? Track your progress (saved only in your browser).