Auto-configuration adds bean definitions when its conditions match the application’s classes, properties and existing beans.
Spring Boot auto-configuration: conditions and user-defined beans
This lesson uses the downloadable source kit: Java 21, Spring Boot 4.0.8 and its managed Spring Framework 7 dependencies. The version is pinned for repeatable builds.
Observe both branches
FallbackExportConfig supplies an exporter only when an Exporter bean is missing. ApplicationContextRunner checks the empty case and the user-supplied case in separate contexts. The second case must contain exactly one exporter, with the user implementation selected.
The fixture is a small conditional configuration used to expose the missing-bean rule. It is not packaged as a reusable Boot auto-configuration starter. Publishing one requires the correct registration metadata, ordering and isolated consumer tests.
Classpath changes affect assembly
Adding a starter can change the available classes and consequently the assembled object graph. A successful old test with a different dependency set is not evidence that the new graph is equivalent. Inspect the selected conditions when assembly differs from the intended design.
The receipt application defines its SecurityFilterChain rather than relying on an unspecified default policy. Security behavior is checked with actual requests, because knowing which bean exists is weaker than knowing what a request can access.
Checked source
package in.aitrove.learning;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@Configuration(proxyBeanMethods = false)
public class FallbackExportConfig {
@Bean @ConditionalOnMissingBean(ContainerContracts.Exporter.class)
ContainerContracts.Exporter fallbackExporter() { return () -> "fallback"; }
}Test the boundary
Run mvn test in the source-kit directory. CoreBoundaryTest.fallbackBeanBacksOffWhenUserBeanExists checks the behavior described here. Java excerpts belong to the named source-kit classes; they are not independent source files unless the complete class is shown.
Costs and boundaries
The runner creates two small contexts rather than starting two servers. This keeps the test focused on conditional bean creation; it does not check routing, serialization or deployment behavior.
Common Mistakes
- Test both the matching and non-matching condition.
- Do not present a conditional configuration class as a complete published starter.
- A new dependency can change assembly behavior.
Read next
Spring qualifiers: select a collaborator when types are ambiguous, Context testing, Security filter chain.
Extend the tested workflow
Continue with Spring Boot auto-configuration: register imports and let a user bean win.
