Sub topic 12
Profiles and conditional bean registration
This chapter assumes you can define beans with @Component and @Bean, and that you know how the ApplicationContext builds singletons at startup. It also assumes you have seen @Primary and @Qualifier. Here you will learn how to make the set of beans in a context depend on the environment or on the configuration.
Why bean registration needs conditions
A real application runs in several places: a developer laptop, a CI server and production. Each place needs different beans. Locally you may want a MessageSender that prints to the console. In production you want one that talks to an SMTP server.
You could write if statements inside one bean. That puts environment checks in business code and keeps both implementations loaded everywhere. Spring instead decides at startup which bean definitions to register. Beans that fail their condition are never created, and nothing else can inject them.
Spring offers two mechanisms:
- Profiles are named groups of beans that you switch on or off by name.
- Conditions are arbitrary rules, such as "this property is set" or "this class is on the classpath", evaluated for a single bean or configuration class.
A profile is a built-in condition. Both mechanisms run while Spring registers bean definitions, before any bean is instantiated.
Declaring profiles with @Profile
@Profile can go on a component class, on a @Configuration class or on a single @Bean method.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
public interface MessageSender {
void send(String to, String body);
}
@Configuration
public class SenderConfig {
@Bean
@Profile("dev")
public MessageSender consoleSender() {
return (to, body) -> System.out.println("console to " + to + ": " + body);
}
@Bean
@Profile("prod")
public MessageSender smtpSender() {
return (to, body) -> {
// a real implementation would call an SMTP client here
System.out.println("smtp to " + to + ": " + body);
};
}
}When you put @Profile on a @Configuration class, the whole class is skipped unless the profile is active. Every @Bean method and every @Import inside it goes with it.
The same rule applies to stereotype classes:
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("dev")
public class DevDataSeeder {
// loads sample rows; never registered in prod
}Profile expressions
The value of @Profile is a profile expression, not only a name.
| Expression | Registered when | Column |
|---|---|---|
| `"dev"` | `dev` is active | |
| `"!prod"` | `prod` is not active | |
| `"prod & cloud"` | both `prod` and `cloud` are active | |
| `"dev \ | test"` | either `dev` or `test` is active |
| `"prod & (eu \ | us)"` | `prod` is active, plus `eu` or `us` |
You cannot mix & and | in one expression without parentheses. Spring rejects "a & b | c" with an IllegalArgumentException at startup. You can also pass several names, as in @Profile({"dev", "test"}). That means "any of these", the same as |.
Activating profiles
A profile only matters once someone activates it. The Environment holds the active profiles, and there are several ways to set them.
| Method | Example |
|---|---|
| Property in Spring Boot | `spring.profiles.active=dev` in `application.properties` |
| JVM argument | `-Dspring.profiles.active=prod` |
| Environment variable | `SPRING_PROFILES_ACTIVE=prod` |
| Command-line argument (Boot) | `--spring.profiles.active=prod` |
| Code, before refresh | `ctx.getEnvironment().setActiveProfiles("dev")` |
| Tests | `@ActiveProfiles("test")` |
In plain Spring, without Boot, you must set the profile before the context refreshes. The refresh is when the conditions are evaluated.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext()) {
ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(SenderConfig.class);
ctx.refresh();
ctx.getBean(MessageSender.class).send("ana", "Welcome!");
}
}
}This prints console to ana: Welcome!. If you pass "prod" instead, you get the SMTP version. Passing the configuration class to the AnnotationConfigApplicationContext constructor would refresh immediately. That is why this example uses the no-argument constructor, register and refresh separately.
The default profile
If no profile is active, Spring treats the profile named default as active. A bean marked @Profile("default") is therefore the fallback for a run with no configuration. Once you activate any profile, the default profile turns off.
Profile-specific properties in Spring Boot
Boot also loads application-{profile}.properties (or .yml) on top of application.properties when that profile is active. A file such as application-prod.properties can override mail.host for production only. Combined with @ConfigurationProperties from the previous chapter, the same MailProperties record then binds different values per environment, with no code change.
Boot supports profile groups, which activate several profiles under one name:
spring.profiles.group.prod=proddb,prodmqRunning with prod now activates prod, proddb and prodmq.
Conditions beyond profiles
Profiles answer "which environment is this?" Conditions answer more specific questions. The core mechanism is @Conditional, which takes one or more Condition classes.
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class OnLinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String os = context.getEnvironment().getProperty("os.name", "");
return os.toLowerCase().contains("linux");
}
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PlatformConfig {
@Bean
@Conditional(OnLinuxCondition.class)
public String platformName() {
return "linux";
}
}Spring Boot ships ready-made conditions so you rarely write your own. These are the most common:
| Annotation | Bean registered when |
|---|---|
| `@ConditionalOnProperty` | a property exists or has a given value |
| `@ConditionalOnMissingBean` | no bean of that type is already defined |
| `@ConditionalOnBean` | a bean of that type is already defined |
| `@ConditionalOnClass` | a class is on the classpath |
| `@ConditionalOnMissingClass` | a class is not on the classpath |
A feature flag is the usual use of @ConditionalOnProperty:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record AuditLog(String target) {
}
@Configuration
public class AuditConfig {
@Bean
@ConditionalOnProperty(prefix = "feature", name = "audit", havingValue = "true")
public AuditLog auditLog() {
return new AuditLog("audit.log");
}
}The bean exists only when feature.audit=true. If the property is absent, the condition fails. Add matchIfMissing = true if you want the bean registered when the property is not set.
How the evaluation works
The diagram shows what Spring does for each candidate bean definition during startup.
Conditions see bean definitions, not bean instances. That explains the most common surprise with the Boot conditions.
Gotchas and failure modes
Order matters for @ConditionalOnBean and @ConditionalOnMissingBean
These two conditions inspect the definitions registered so far. If your configuration class is processed before the class that defines the other bean, the check can give the wrong answer. Spring Boot designed these annotations for auto-configuration classes, whose order is controlled. In your own configuration they are fragile. Prefer @Profile or @ConditionalOnProperty there, because those do not depend on the order of other definitions.
A missing profile means a missing bean
If SenderConfig only has dev and prod beans and you run with the profile staging, no MessageSender exists. Startup fails with NoSuchBeanDefinitionException or UnsatisfiedDependencyException, which you saw in the chapter on wiring errors. Two fixes work:
- Cover every environment, for example
@Profile("!prod")for the console sender, so that "not prod" always has a bean. - Add a
@Profile("default")fallback.
Overloaded @Bean methods share one condition
Spring evaluates a condition for a method name, not for each overload. If you have overloaded @Bean methods with the same name and different @Profile values, the condition on the first overload decides for all of them. Give profile-specific beans different method names.
Beans without @Profile are always registered
A component with no @Profile is registered in every environment. Mark anything environment-specific explicitly. Putting DevDataSeeder in a package that component scanning covers, without @Profile("dev"), will seed production data.
Profiles are not a secrets mechanism
A profile selects behavior. It does not protect values. Do not put passwords in application-prod.properties committed to source control. Supply them through environment variables or a secrets store.
Too many profiles
Each profile doubles the number of possible combinations to test. Use profiles for coarse environment choices such as dev, test and prod. Use @ConditionalOnProperty for individual feature flags.
Using profiles in tests
For a Spring context test, activate the profile on the test class:
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(SenderConfig.class)
@ActiveProfiles("dev")
class DevSenderTest {
@Autowired
MessageSender sender;
@Test
void devProfileProvidesSender() {
assertNotNull(sender);
}
}Most logic does not need this. A unit test that builds the object directly, as in the previous chapter, is faster. Use profile-based context tests only to check the wiring itself: that the right bean appears under the right profile.
Exercise
A configuration class declares @Bean @Profile("dev") MessageSender consoleSender() and @Bean @Profile("prod") MessageSender smtpSender(). The application starts with SPRING_PROFILES_ACTIVE=staging and a service that injects MessageSender. What happens, and what is one way to fix it?
Show answer
Neither bean is registered because neither profile is active, so injecting MessageSender fails at startup with an unsatisfied dependency error (NoSuchBeanDefinitionException). One fix is to change the console bean to @Profile("!prod"), so every non-prod environment gets a sender. Another is to add a @Profile("default") bean, although that does not help here because staging is active and so default is not.
Exercise
Write the @Profile expression for a bean that must exist when prod is active and either eu or us is also active. Then explain why "prod & eu | us" is invalid.
Show answer
Use @Profile("prod & (eu | us)"). Spring does not allow & and | in the same expression without parentheses, because the intended grouping would be ambiguous. It rejects "prod & eu | us" at startup with an IllegalArgumentException.
Exercise
Why is @ConditionalOnMissingBean unreliable in your own application configuration but fine in Spring Boot auto-configuration?
Show answer
The condition looks at the bean definitions registered so far, and the result depends on the order in which configuration classes are processed. Boot controls the order of auto-configuration classes, so the check is predictable there. In application code the order is harder to guarantee, so the condition can pass or fail depending on processing order.