Sub topic 12
Profiles and conditional bean registration
This chapter assumes you can define beans with @Component and @Bean, and that you know how Spring resolves injection by type. Here you will choose which beans exist in a given environment.
Why register beans conditionally
A real application needs different beans in different places. Tests may use a fake sender, while production uses a real one. Spring decides this while it builds the container. A bean that is not registered does not exist at all.
Profiles
A profile is a named group of bean definitions. A bean annotated with @Profile is registered only when that profile is active.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class SenderProfiles {
@Bean
@Profile("dev")
public MessageSender consoleSender() {
return (to, body) -> System.out.println("console: " + body);
}
@Bean
@Profile("!dev")
public MessageSender smtpSender() {
return (to, body) -> System.out.println("smtp to " + to + ": " + body);
}
}@Profile("!dev") means "any time dev is not active". You can also put @Profile on a @Component class or on a whole @Configuration class. Expressions such as @Profile("prod & eu") combine profiles with & and |.
Activating profiles
In Spring Boot, set the property spring.profiles.active=dev in application.properties, as an environment variable SPRING_PROFILES_ACTIVE, or as a command-line argument. Without the Boot property, set the profile on the environment before the context refreshes.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ProfileMain {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext()) {
ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(SenderProfiles.class);
ctx.refresh();
ctx.getBean(MessageSender.class).send("ana", "Hello");
}
}
}Passing the configuration class to the constructor refreshes the context immediately. That is why this example registers the class and calls refresh() itself, after the profile is set.
Conditional registration
Profiles are one kind of condition. The general mechanism is @Conditional, which takes a Condition class that returns true or false. Spring Boot builds ready-made annotations on it:
| Annotation | Registers the bean when |
|---|---|
| `@ConditionalOnProperty` | a property has a given value |
| `@ConditionalOnMissingBean` | no bean of that type exists yet |
| `@ConditionalOnClass` | a class is on the classpath |
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeatureConfig {
@Bean
@ConditionalOnProperty(name = "feature.sms", havingValue = "true")
public MessageSender smsSender() {
return (to, body) -> System.out.println("sms: " + body);
}
@Bean
@ConditionalOnMissingBean(MessageSender.class)
public MessageSender fallbackSender() {
return (to, body) -> System.out.println("log: " + body);
}
}@ConditionalOnMissingBean is evaluated in definition order. It works reliably in auto-configuration classes, which Boot processes after your own beans. In ordinary configuration it can give surprising results.
Common errors
- Activating the profile too late. Setting profiles after
refresh()has no effect on beans already registered. - No bean in some profile. If every
MessageSenderhas a profile and none is active, injection fails withNoSuchBeanDefinitionException. Beans without@Profileare always registered, and adefaultprofile covers the case where none is set. - Two beans in one profile. Overlapping profiles can leave two candidates for one type. Use
@Primaryor@Qualifierfrom the previous chapter. - Misspelled profile names. Spring does not warn about a profile that nothing defines.
Exercise
A class ProdMailer is annotated @Profile("prod") and is the only MessageSender bean. The application starts with no active profile, and NotificationService requires a MessageSender. What happens, and how can you fix it?
Show answer
Startup fails with NoSuchBeanDefinitionException, because ProdMailer is not registered when prod is inactive. Fix it by activating prod, or by adding another MessageSender bean for the other profiles, for example one annotated @Profile("!prod").