Sub topic 2
Backing off when the user defines a bean
Assume you know Java, dependency injection, @Configuration and @Bean, and how to run a Spring Boot application. The key rule is that auto-configuration supplies a default, but it should not override an explicit application choice.
Backing off with bean conditions
@ConditionalOnMissingBean makes a bean method conditional. Spring creates the bean only when no matching bean already exists.
@AutoConfiguration
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService() {
return new GreetingService("Hello");
}
}If the application declares its own GreetingService, Spring skips this method. This behavior is called backing off.
| Condition | Auto-configuration behavior |
|---|---|
| No `GreetingService` exists | Create the default bean |
| The application defines one | Skip the default bean |
@ConditionalOnBean does the opposite check. It applies configuration when a required bean exists:
@ConditionalOnBean(DataSource.class)Use bean conditions mainly inside auto-configuration classes. Application configuration is processed in a broader context, so an existing bean may not yet be visible when the condition is evaluated.
Switching behavior with properties
@ConditionalOnProperty lets configuration follow an environment property. The following configuration is enabled by default but can be disabled with greeting.enabled=false.
@ConditionalOnProperty(
prefix = "greeting",
name = "enabled",
havingValue = "true",
matchIfMissing = true
)matchIfMissing = true determines what happens when the property is absent. Choose this default deliberately because it controls behavior in every application that does not set the property.
When conditions are evaluated
Spring Boot evaluates conditions during configuration processing. Some conditions inspect the classpath or properties early. Bean conditions depend on bean definitions that have already been registered.
Controlling auto-configuration order
Use before and after on @AutoConfiguration when one auto-configuration must be processed relative to another.
@AutoConfiguration(after = DataSourceAutoConfiguration.class)
@ConditionalOnBean(DataSource.class)
public class AuditAutoConfiguration {
}Processing after DataSourceAutoConfiguration gives the bean condition a chance to see its DataSource definition. Ordering solves visibility problems; it does not guarantee that a bean has already been instantiated.
Exercise
Why should a custom auto-configuration use @ConditionalOnMissingBean for its default service?
Show answer
It lets the application define its own service while the auto-configuration supplies one only when needed.