The Silent Override: When Your @Bean Definition Loses Without a Fight
The application starts in 4.2 seconds. No stack traces. The banner prints, the actuator health endpoint returns UP, and the Hikari pool reports ten idle connections. Then the on-call engineer notices that the orders table is empty. Not "missing rows" empty. Empty as in, the table does not exist on the production PostgreSQL cluster, and a SELECT against it from psql confirms it. Yet the application is happily inserting rows somewhere, because the integration smoke test just passed.
That somewhere is an in-memory H2 database living inside the JVM. The PostgreSQL DataSource declared in DataSourceConfig.java, the one wired with the production JDBC URL pulled from Vault, the one code review approved last Tuesday, is not the bean Hikari is wrapping. Spring Boot built a different DataSource at startup, registered it under the same type, and handed it to every @Autowired consumer in the context1, 2. The code on disk says PostgreSQL. The running process says H2. Both are true at the same time, and neither the compiler nor the Spring container raised a single complaint3.
This is the failure mode that erodes trust in a framework. A NullPointerException is a gift; it tells you where to look. A clean log with the wrong runtime behavior is harder, because what you need to debug is the gap between what the source code declares and what the container actually built. The reflex is to suspect the profile, the property file, the classpath, the build. The real culprit sits one layer deeper, inside an annotation that almost no application developer writes themselves but every Spring Boot app inherits hundreds of: @ConditionalOnMissingBean.
The annotation does exactly what its name says. It registers the annotated bean only if no bean of the specified type or name already exists at the moment the condition is evaluated [4][3]. The design intent is generous: library authors ship a sensible default, and any consumer who declares their own bean of the same type silently wins [5][4]. Define your own DataSource, and Spring Boot's auto-configured one steps aside without a word. That is the contract.
The contract has a sharp edge. "At the moment the condition is evaluated" is doing enormous work in that sentence. If your @Configuration class has not been processed by the time DataSourceAutoConfiguration runs its check, or if the bean you declared is registered under a type the condition does not match against, or if a test slice quietly excludes your configuration while leaving the H2 driver on the classpath, the condition resolves as "missing" and the auto-configured default wins [2][6]. Your @Bean method is still in the source tree. It is still compiled into the jar. It is simply never invoked, because something else got there first and the override mechanism that was supposed to defer to you never saw you in time.
How Auto-Configuration Actually Works: The @ConditionalOnMissingBean Trap#
The annotation itself is not the villain. Ordering is.
@ConditionalOnMissingBean is a deferred check: when Spring parses a @Configuration class, it asks the bean factory whether a matching bean already exists, and if one does, it skips registering the annotated definition. This works because auto-configuration classes are guaranteed to be parsed last, after every user-defined @Configuration and every component-scanned class has already contributed its bean definitions [7]. By the time DataSourceAutoConfiguration is evaluated, your custom DataSource bean is already in the registry, the condition reports "present," and the auto-configured default bows out. That is the contract Spring Boot's authors designed around, and on the happy path it holds.
The contract breaks the moment you place @ConditionalOnMissingBean somewhere other than an auto-configuration class. Consider a component-scanned bean that tries to declare itself a default:
This bean will not be registered even when no other bean named ServiceA exists anywhere in the application [7]. The reason is that component scanning processes classes in an order Spring does not guarantee. When the condition fires for ServiceA, the scanner has only seen a subset of candidates so far, and the matching logic has no way to know what is coming next. A sibling ServiceB that omits the condition registers without issue [8]. The Spring Boot reference documentation states this plainly, though the warning is easy to miss: on regular @Configuration classes, "care must be taken not to refer to bean definitions that have not yet been created" [7]. In practice, @ConditionalOnMissingBean only behaves predictably on a class that Spring is guaranteed to parse last. Auto-configuration classes get that guarantee. Yours do not.
There is a second failure mode that catches engineers writing custom starters. If you register beans programmatically through ConfigurableBeanFactory.registerSingleton(), those singletons are invisible to @ConditionalOnMissingBean [9]. The condition checks bean definitions, not the singleton cache, so a bean injected at runtime from a BeanFactoryAware hook will not suppress the auto-configured default even though it is functionally present in the context [10]. You end up with two beans of the same type: your dynamically registered one and Spring Boot's fallback. The resulting NoUniqueBeanDefinitionException, or worse, a silent wrong-autowiring choice, feels like a framework bug. It is not. It is the cost of bypassing the definition-registration phase the condition was built to inspect.
The pattern is consistent: @ConditionalOnMissingBean answers a question at a specific point in the lifecycle, and the answer is only reliable when the asker is last in line. Auto-configuration classes are last in line by construction. Everything else is a gamble on scan order, and that gamble is what produces runtime behavior that contradicts what the source code appears to say.
The Ordering Problem: Why Your Bean Can Be 'Missing' Even When It Exists#
There is a comforting story Spring Boot developers tell themselves: user beans are always registered before auto-configuration runs, so @ConditionalOnMissingBean will always see them. For the main application context, with a single auto-configuration source, that story holds. The moment you cross a JAR boundary, it falls apart.
Consider the case that breaks the model. Two libraries on the classpath, each contributing an auto-configuration. my-package-mock.jar ships AutoConfigurationA, which registers a mock MyService and is annotated @AutoConfigureBefore(AutoConfigurationB.class). my-package-real.jar ships AutoConfigurationB, which uses @ConditionalOnMissingBean(MyService.class) to register the real implementation [11]. The intent is obvious: when the mock jar is present, the mock wins; when it is absent, the real service registers itself. A clean swap, controlled by a dependency.
It does not work. Pull both jars into a third project and the ordering annotation gets quietly ignored at load time. AutoConfigurationB is processed first, MyService is not yet defined, and the real service registers itself before AutoConfigurationA ever runs [12]. Your mock loses to whichever class the JVM happened to load first. The behavior is not wrong, exactly. It is non-deterministic, which in production terms is the same thing.
The mechanism is worth being precise about. @AutoConfigureBefore and @AutoConfigureAfter only constrain ordering among auto-configurations that Spring Boot's AutoConfigurationImportSelector sees as a sortable set. When the annotations are declared on configuration classes discovered through spring.factories (or AutoConfiguration.imports on newer versions), they are respected. When one of the configurations is picked up as an ordinary @Configuration through component scanning instead of through the auto-configuration import mechanism, the ordering contract no longer applies. Classpath order takes over, and classpath order is a function of how your build tool resolved the dependency graph that morning.
This is also why the problem can appear to fix itself for the wrong reason. Move your @SpringBootApplication class out of org.packages.package and into org.somewhereelse, and suddenly the mock wins reliably [13]. It looks like a fix. What changed is the package scan scope: the component scan rooted at the main class no longer picks up AutoConfigurationA or AutoConfigurationB as regular @Configuration classes, so both are processed only through the auto-configuration pipeline, where @AutoConfigureBefore is honored. Move the main class back, or add a new package, and the bug returns. You did not solve the ordering problem. You hid it behind a coincidence of package layout.
The diagnostic implication is uncomfortable. Reading the source code of either jar in isolation tells you nothing about which bean will win at runtime. You need to know which configurations are auto-configurations versus component-scanned, the order in which the importer sorts them, and whether any third-party jar on the classpath has injected itself into that ordering. None of this is visible in the code under your cursor. What you need instead is a way to ask the running application what actually happened.
Diagnosing the Problem: The --debug Flag and the CONDITIONS EVALUATION REPORT#
Reading source code will not tell you which bean won. The classpath will not tell you either, not directly. What you need is the report Spring Boot already generates internally on every startup but hides from your console by default.
Turn it on. You can set debug=true in application.properties, pass --debug on the command line, or raise the logging level of org.springframework.boot.autoconfigure.logging to DEBUG. The three approaches are interchangeable, so pick whichever fits your workflow [14]. On the next startup, somewhere in the output, you will find a block titled CONDITIONS EVALUATION REPORT, split into Positive matches, Negative matches, and Unconditional classes.
This report is the audit log Spring should have shown you all along. For every auto-configuration class Spring Boot considered, it records the verdict and the reason. A positive match for DataSourceAutoConfiguration will list each @Conditional that passed: @ConditionalOnClass found DataSource, @ConditionalOnMissingBean found no existing DataSource bean at the moment it checked, and so on. A negative match tells you precisely which condition failed and what Spring saw when it failed.
That second case is where the silent override becomes visible. If your hand-written DataSource got steamrolled, you will see DataSourceAutoConfiguration under Positive matches with a note that @ConditionalOnMissingBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans. That single line is the smoking gun. Spring evaluated the condition before your @Configuration class registered its bean, decided nothing existed, and proceeded to wire its own. The source code you were reading was never wrong. The order of operations was.
The same report answers the inverse question. If your custom bean did win, you will find the relevant auto-configuration under Negative matches with a reason like @ConditionalOnMissingBean found beans of type 'javax.sql.DataSource' dataSource. Now you know the override did not happen, and you can stop suspecting auto-configuration and start looking elsewhere.
Two practical notes. The report is verbose; on a real application it can run to several hundred lines, and grepping for the bean type you care about (grep -A2 DataSource) is faster than scrolling. You also almost certainly do not want this enabled in production, so once you have diagnosed the problem, drop the logging level back to INFO or remove the property entirely [14].
Diagnosis is half the job. Knowing which auto-configuration won, and why, tells you nothing about how to make your bean win instead.
Taking Back Control: Four Patterns to Win the Bean Resolution Race#
The right fix depends on whether you are an application engineer fighting Spring Boot's defaults or a library author trying to ship a default that bends to your users.
Exclude the auto-configuration outright. When you know you do not want DataSourceAutoConfiguration to participate at all, say so explicitly. @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) removes the class from consideration before any condition is evaluated. No race, no ordering puzzle, no surprise wiring. This is the bluntest tool, and it is the right one when your application defines a bean that has nothing in common with Spring Boot's defaults beyond the type signature.
**Put your @Bean in a @Configuration class that is component-scanned by your main application class.** Spring Boot's promise that auto-configuration classes are always parsed last holds only when your configuration is part of the scan rooted at @SpringBootApplication [7]. A @Bean DataSource declared in a properly scanned class will be registered before DataSourceAutoConfiguration runs, and @ConditionalOnMissingBean(DataSource.class) will then correctly evaluate to false and skip the default [4]. The fix for most of the bugs described here is usually this simple: move the bean out of an isolated @Configuration living outside the scan and into one that lives inside it.
**Use @Primary when you genuinely want both beans to exist.** If a library registers a RestTemplate and you want yours injected by default while still keeping the library's bean available for explicit @Qualifier lookups, @Primary on your @Bean method is the cleanest signal. This is not about winning the conditional race. It is about deciding what happens when the race produces two finishers.
**For library authors: put @ConditionalOnMissingBean on the @Bean method, registered through AutoConfiguration.imports.** If you are shipping a starter, put @ConditionalOnMissingBean on the @Bean method inside an auto-configuration class registered via META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (or spring.factories on Boot 2.x), not on a @Component that gets picked up by user component scans [15][16]. The auto-configuration mechanism is what guarantees your config is parsed after the user's. A component-scanned @ConditionalOnMissingBean class has no such guarantee [7].
When two libraries collide and both want to register the same bean type, @AutoConfigureBefore is the tiebreaker. The mock-versus-real example from earlier illustrates the pattern: the higher-priority configuration carries @AutoConfigureBefore(RealAutoConfiguration.class) and registers its bean unconditionally; the lower-priority configuration carries @ConditionalOnMissingBean and registers its bean as a fallback [11][12]. Skip the ordering hint and the JVM's classloader order picks the winner, which is to say no one picks it.
The next time you start a Spring Boot service, do not wait for production to surface the mismatch. Make --debug part of your local bootstrap routine: start the app with the flag, grep the CONDITIONS EVALUATION REPORT for every auto-configuration whose bean type your team owns, and confirm each one appears under "Negative matches" with a @ConditionalOnMissingBean reason that cites your bean. Better yet, write a context integration test that boots the application with debug output captured to a buffer and asserts those negative matches by name. The test fails the day someone moves your DataSource configuration outside the component scan, or the day a new starter on the classpath quietly takes over a bean you thought was yours. The goal is not to memorize four patterns. The goal is to stop trusting that the code you read is the code that runs, and to make that distrust executable.
Sources
- Data Access :: Spring Bootdocs.spring.io
- The simplest way to replace H2 with a real database for testingtestcontainers.com
- [Anshika Singh (@anshikasingh625494): "💡 Annotation @ConditionalOnMissingBean in Spring Boot.
Keep reading
How to Scale a Spring Boot App to 1 Million Requests Per Minute
Spring Boot is a Java framework for building web services, and its out-of-the-box configuration is tuned for developer convenience, not production throughput. This article...
How Spring Security works with JWT, OAuth2, and SSO
Spring Security is a framework that intercepts every HTTP request entering your application and enforces authentication and authorization rules before that request ever reaches a...
30 Seconds of Nothing: Why Spring Boot's Startup Log Tells You Almost Nothing
You audit every @PostConstruct method. You strip out the ones doing redundant work. You rerun the app, watch the terminal, and see: Started Application in 34.2 seconds. That...