Sub topic 11
Choosing beans per profile with @Profile
The previous chapters covered how profiles are activated and how profile-specific files change property values. This chapter covers the other half of profiles: changing which beans exist. It assumes you can write @Configuration classes and @Bean methods, and that you know how to activate a profile with spring.profiles.active.
What @Profile does
@Profile is a condition on bean registration. When Spring builds the application context, it checks the annotation against the active profiles. If the condition is false, the bean definition is skipped and no instance is ever created. The bean doesn't exist, so it can't be injected.
This differs from changing a property. A property override changes how a bean behaves. @Profile decides whether the bean is there at all. Use it when the implementations differ, such as a console logger in development and an SMTP client in production.
You can put @Profile in three places:
- On a
@Beanmethod, which affects only that bean. - On a
@Configurationclass, which affects every@Beanmethod in it. - On a stereotype class such as
@Component,@Serviceor@Repository.
Swapping implementations
The example below defines one interface and two implementations. Exactly one is registered, depending on the active profile.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
interface Notifier {
void send(String message);
}
@Configuration
class NotifierConfig {
@Bean
@Profile("!prod")
Notifier loggingNotifier() {
return message -> System.out.println("[dev] " + message);
}
@Bean
@Profile("prod")
Notifier emailNotifier(MailProperties mail) {
return message -> System.out.println("Sending via " + mail.host() + ": " + message);
}
}MailProperties is the validated @ConfigurationProperties record from the earlier chapters. emailNotifier receives it as a method parameter. The two bean methods have different names, but the profile conditions are what keep them from clashing.
A consumer depends only on the interface and never mentions profiles:
import org.springframework.stereotype.Service;
@Service
class AlertService {
private final Notifier notifier;
AlertService(Notifier notifier) {
this.notifier = notifier;
}
void raise(String text) {
notifier.send(text);
}
}Keep profile awareness inside configuration classes. If business code never checks which profile is active, you can test it with any Notifier.
Profile expressions
The string you pass to @Profile is a profile expression, not just a name. These operators are supported:
| Expression | Meaning | Column |
|---|---|---|
| `prod` | `prod` is active | |
| `!prod` | `prod` is not active | |
| `dev & cloud` | both `dev` and `cloud` are active | |
| `dev \ | test` | at least one of `dev` or `test` is active |
| `(dev \ | test) & !cloud` | parentheses group sub-expressions |
You can't mix & and | in one expression without parentheses. dev | test & cloud fails at startup with an error about the expression, so write dev | (test & cloud) or the other grouping.
Passing several values, as in @Profile({"dev", "test"}), means OR. A single string with | means the same thing. Pick one style and use it consistently.
Here is a stereotype example that runs only in two profiles:
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("dev | test")
class DemoDataLoader implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Loading demo data");
}
}The default profile
If no profile is active, Spring treats the profile named default as active. You can target that case directly:
@Bean
@Profile("default")
Notifier consoleNotifier() {
return message -> System.out.println(message);
}The default profile switches off as soon as any other profile is activated, including a profile that has nothing to do with this bean. If you activate only metrics, a bean marked @Profile("default") disappears. For "everything except production", !prod is usually the safer choice, as in the example above.
Running it
Start the application without a profile and loggingNotifier is registered. Activate prod and emailNotifier replaces it:
java -jar app.jar
java -jar app.jar --spring.profiles.active=prodIn the second case the prod document in application.yaml also supplies the production mail host and port. The profile therefore changes which bean exists and which values it receives.
Reading profiles in code
Sometimes you need to branch on the profile inside a method, for example to log a warning at startup. Inject Environment and use acceptsProfiles:
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
@Configuration
class StartupReport {
@Bean
CommandLineRunner profileReport(Environment env) {
return args -> {
boolean prod = env.acceptsProfiles(Profiles.of("prod"));
System.out.println("Production mode: " + prod);
};
}
}Profiles.of accepts the same expression syntax as @Profile. Prefer @Profile on beans over if checks in code, because the conditions then show up in one place and appear in the condition evaluation report.
Testing profile-dependent beans
Tests have no profile active unless you ask for one, so a test sees the !prod beans by default. Use @ActiveProfiles to choose a different set. The test below checks which bean was registered:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest
@ActiveProfiles("prod")
class NotifierSelectionTest {
@Autowired
ApplicationContext context;
@Test
void registersOnlyTheEmailNotifier() {
assertThat(context.getBeansOfType(Notifier.class).keySet())
.containsExactly("emailNotifier");
}
}Remove @ActiveProfiles and the assertion would need to expect loggingNotifier. The test class must sit in the same package as Notifier, because the interface is package-private.
Common errors
- No qualifying bean. Every condition is false for the active profiles, so no
Notifierexists and injection fails. This happens with@Profile("dev")and@Profile("prod")when you run withstaging. Cover every case, for example with!prod. - More than one bean. Two conditions overlap, such as
@Profile("dev")next to@Profile("!prod")whendevis active. Spring then throwsNoUniqueBeanDefinitionException. Make the conditions mutually exclusive. - Profile on a class, not its methods. A
@Profileon the@Configurationclass overrides nothing and wins over nothing. If the class condition is false, its@Beanmethods are never read, whatever their own annotations say. - Typos in profile names. A misspelled name is simply never active, and Spring gives no warning. Keep the names as constants or check them against the startup log line "The following profiles are active".
- Too many profile-gated beans. If a bean differs only by a value such as a URL, use a property and keep one bean. Reserve
@Profilefor different implementations.
Exercise
An application has @Bean @Profile("dev") Notifier a() and @Bean @Profile("!prod") Notifier b(). It starts with --spring.profiles.active=dev. What happens, and how would you fix it?
Show answer
Both conditions are true when dev is active, so two Notifier beans are registered. Any injection point that asks for a single Notifier fails with NoUniqueBeanDefinitionException. Fix it by making the conditions exclusive, for example @Profile("dev") and @Profile("!dev & !prod"), or by removing one of the beans.
Exercise
Write a profile expression for a bean that should exist when either dev or test is active, but never when cloud is also active.
Show answer
(dev | test) & !cloud. The parentheses are required because & and | can't be mixed in one expression without grouping.