A developer asks an AI coding assistant to add a secondary read-only database connection for a reporting endpoint. Ten seconds later, the assistant produces a neat @Configuration class with a @Bean fun reportingDataSource(): DataSource.

The unit tests pass. The integration slice tests pass. Code review looks clean. Production deploys with zero warnings, and your primary Hikari pool silently drops from 25 tuned connections down to Hikari’s default of 10.

In Part 1 we mapped why Spring Boot 4 allows valid YAML properties to bind cleanly while their auto-configured consumers back off, and in Part 2 we showed how to catch upgrade drift with a before-and-after /actuator/conditions diff. One-off migration checks stop a cutover outage, yet they decay the moment the next feature branch lands.

To keep auto-configuration honest permanently, you need automated contract tests that run in milliseconds and fail the build the instant a critical line in application.yml loses its consumer.

Why Classic Unit Tests and @MockitoBean Hide @Conditional Bugs

Most Spring Boot codebases sit in an awkward testing gap:

  • Plain unit tests construct classes directly with new, so Spring never evaluates a single @ConditionalOnClass, @ConditionalOnProperty, or @ConditionalOnMissingBean.
  • Web or service tests using @MockitoBean (formerly @MockBean) actively hide the bug. Registering @MockitoBean lateinit var dataSource: DataSource or @MockitoBean lateinit var cacheManager: CacheManager puts a mock bean of that type into the context, satisfying @ConditionalOnMissingBean and turning off the exact auto-configuration you thought your suite was exercising.
  • Full end-to-end suites with Testcontainers exercise the real wiring, but they are too slow and heavyweight to test every combination of missing dependencies, Servlet versus WebFlux runtimes, or profile overrides.

Closing that gap takes three lightweight layers, all runnable without Docker or external brokers (every test snippet below is verified against Spring Boot 4.0.10 in the open-source companion repository github.com/grupavii/boot-truth).

Tier 1 (~50 ms): ApplicationContextRunner for Fast Contract Proofs

Spring Boot ships ApplicationContextRunner, WebApplicationContextRunner, and ReactiveWebApplicationContextRunner specifically for testing auto-configuration decisions without starting Tomcat, Netty, or a database. Each test runs in roughly 50 milliseconds and lets you manipulate classpath visibility (FilteredClassLoader), properties, and user beans with surgical precision.

Proof 1: Catching Silent Cache Fallback with FilteredClassLoader

Want to prove what happens if someone accidentally drops Caffeine from build.gradle.kts? Simulate the missing dependency in one line:

@Test
fun `pinning spring cache type=caffeine fails fast when Caffeine is missing`() {
    ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration::class.java))
        .withUserConfiguration(CachingEnabledConfig::class.java)
        .withClassLoader(FilteredClassLoader(Caffeine::class.java))
        .withPropertyValues(
            "spring.cache.type=caffeine",
            "spring.cache.caffeine.spec=maximumSize=1000,expireAfterWrite=5m",
        )
        .run { context ->
            assertThat(context).hasFailed()
            assertThat(context.startupFailure)
                .hasMessageContaining("No cache manager could be auto-configured")
        }
}

Remove "spring.cache.type=caffeine" from that exact test, and the context boots cleanly with ConcurrentMapCacheManager, proving why pinning the cache provider type is non-negotiable.

Proof 2: Verifying DataSource Isolation with defaultCandidate = false

Here is the fast proof for the auxiliary DataSource trap (and its Spring Framework 6.2 / Boot 4 fix):

@Configuration(proxyBeanMethods = false)
class AuxiliaryNonDefaultDataSourceConfig {
    @Bean(defaultCandidate = false)
    fun reportingDataSource(): DataSource =
        DataSourceBuilder.create()
            .type(HikariDataSource::class.java)
            .url("jdbc:h2:mem:reporting")
            .build()
}

@Test
fun `marking auxiliary DataSource defaultCandidate=false preserves Hikari auto-configuration`() {
    ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration::class.java))
        .withUserConfiguration(AuxiliaryNonDefaultDataSourceConfig::class.java)
        .withPropertyValues(
            "spring.datasource.url=jdbc:h2:mem:primary",
            "spring.datasource.hikari.maximum-pool-size=25",
            "spring.datasource.hikari.connection-timeout=5000",
        )
        .run { context ->
            val primary = context.getBean(DataSource::class.java) as HikariDataSource
            assertThat(primary.maximumPoolSize).isEqualTo(25)
            assertThat(primary.connectionTimeout).isEqualTo(5_000L)
        }
}

Without defaultCandidate = false, DataSourceAutoConfiguration backs off on @ConditionalOnMissingBean(DataSource.class) and maximumPoolSize quietly falls back to 10.

Proof 3: Servlet vs. Reactive Security and Kafka Virtual Threads

The same 50-millisecond pattern locks down platform starters across Servlet and WebFlux runtimes:

  • Use ReactiveWebApplicationContextRunner to verify that a shared security starter annotated @ConditionalOnWebApplication(type = SERVLET) does not leave a WebFlux service unprotected (asserting SecurityWebFilterChain is present).
  • Use ApplicationContextRunner with KafkaAutoConfiguration to assert that a custom kafkaListenerContainerFactory delegates to ConcurrentKafkaListenerContainerFactoryConfigurer, preserving both spring.kafka.listener.concurrency and the SimpleAsyncTaskExecutor wired by spring.threads.virtual.enabled=true.
  • Use ReactiveWebApplicationContextRunner with RSocketServerAutoConfiguration to prove that RSocketServerCustomizer is registered whenever spring.rsocket.server.transport=websocket runs over WebFlux without a dedicated spring.rsocket.server.port.

Tier 2: One InfrastructureContractTest on the Real @SpringBootTest

ApplicationContextRunner tests individual auto-configurations in isolation. It does not catch a surprise interaction caused by your full service classpath, an internal platform BOM, or a profile-specific application-prod.yml.

Pair Tier 1 with one focused @SpringBootTest per service that boots the real application context (with zero @MockitoBean overrides on infrastructure beans) and checks the five to ten deadliest configuration contracts in one pass:

@SpringBootTest
@ActiveProfiles("contract")
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
class InfrastructureContractTest(
    private val context: ConfigurableApplicationContext,
) {
    @Test
    fun `critical yaml configuration must actually be wired into live beans`() {
        BootTruthAssertions.verify(context)
            .assertNoOrphanedProperties()
            .assertLivePropertiesApplied()
            .assertNoSilentCacheFallback()
            .assertHikariPoolConfigApplied(
                expectedMaxPoolSize = 25,
                expectedConnectionTimeoutMs = 5_000L,
            )
            .assertKafkaListenerConfigApplied(
                expectedConcurrency = 4,
                expectVirtualThreads = true,
            )
            .assertSecurityFilterChainPresent()
    }
}

Because Spring TestContext caches the application context across test classes sharing the same configuration, this test adds almost zero overhead to an existing integration suite while acting as a hard tripwire against silent regressions.

Rule of thumb: Never mock DataSource, CacheManager, SecurityFilterChain, or KafkaListenerContainerFactory inside your infrastructure contract test. If you mock the bean, you silence the condition you came to verify.

Tier 3: The Missing Spring Boot Diagnostic (OrphanedPropertyGuard)

Writing manual assertions for every property works for five settings, yet it still requires every team to remember which auto-configuration consumes which prefix. What Spring Boot still lacks out of the box is an opt-in diagnostic that asks a single question at startup:

Did the operator explicitly configure a high-risk property prefix in Environment while the auto-configuration responsible for consuming it backed off or never loaded?

In boot-truth-core, OrphanedPropertyGuard implements that check directly on Spring Boot’s public ConditionEvaluationReport and ConfigurableListableBeanFactory APIs:

val guard = OrphanedPropertyGuard(rules = BuiltInRules.defaults())
val report = guard.inspect(context.environment, context.beanFactory)
if (report.hasViolations) {
    throw AssertionError(report.formatReport())
}

Each built-in rule pairs one high-risk YAML prefix with its expected Boot 4 auto-configuration consumer. BuiltInRules.defaults() ships 12 curated rules across caching, JDBC, RSocket, Kafka, Security, OTLP/Prometheus observability, R2DBC pooling, RabbitMQ, and Virtual Threads — here are four representative entries:

Rule IDWatched Property PrefixExpected Boot 4 Consumer
BT-CACHE-001spring.cache.caffeineCaffeineCacheConfiguration
BT-JDBC-001spring.datasource.hikariDataSourceConfiguration$Hikari
BT-RSOCKET-001spring.rsocket.server.fragment-sizeRSocketServerAutoConfiguration$EmbeddedServerConfiguration
BT-KAFKA-001spring.kafka.listenerKafkaAnnotationDrivenConfiguration#kafkaListenerContainerFactory

When that opening pull request adds a bare reportingDataSource() bean, CI stops immediately with a diagnostic that points directly to the culprit:

[ERROR] BT-JDBC-001: spring.datasource.hikari.* properties are configured, but DataSourceConfiguration$Hikari backed off (commonly because a custom DataSource bean exists).
  Configured properties : spring.datasource.hikari.maximum-pool-size
  Expected consumers    : DataSourceConfiguration$Hikari
  Observed status       : BACKED_OFF
  Condition details     : DataSourceAutoConfiguration$PooledDataSourceConfiguration: @ConditionalOnMissingBean (types: javax.sql.DataSource; SearchStrategy: all) found beans of type 'javax.sql.DataSource' reportingDataSource
  Remediation           : Mark auxiliary DataSource beans with @Bean(defaultCandidate = false)...

A Subtle Spring Boot 4 Discovery: Parse-Phase Ghost Matches

While building and testing OrphanedPropertyGuard against live Spring Boot 4.0.10 contexts, we hit an internal detail that breaks naive ConditionEvaluationReport checkers.

When a user registers a custom DataSource bean, DataSourceAutoConfiguration$PooledDataSourceConfiguration backs off during the REGISTER_BEAN phase on @ConditionalOnMissingBean(DataSource.class). However, its @Import-ed nested class DataSourceConfiguration$Hikari already passed its PARSE_CONFIGURATION phase checks and therefore remains inside ConditionEvaluationReport.positiveMatches, even though it registered zero beans in the container.

If a guard checks only ConditionEvaluationReport.positiveMatches, DataSourceConfiguration$Hikari looks healthy while your Hikari pool silently reverts to 10 connections.

The fix is a second verification pass against live ConfigurableListableBeanFactory.beanDefinitionNames:

if (matchedSources.isNotEmpty()) {
    if (beanFactory == null || isAnySourceRegisteredInBeanFactory(matchedSources, beanFactory)) {
        return ConsumerEvaluation(ConsumerStatus.MATCHED, emptyList())
    }
    // Parse-phase positive match, but parent backed off and registered zero beans!
    val parentReasons = findRelatedNegativeReasons(matchedSources, outcomesBySource)
    return ConsumerEvaluation(ConsumerStatus.BACKED_OFF, parentReasons)
}

Checking method-level specificity matters just as much. For Kafka, KafkaAnnotationDrivenConfiguration itself stays in positiveMatches even when a user replaces kafkaListenerContainerFactory; only the specific @Bean method KafkaAnnotationDrivenConfiguration#kafkaListenerContainerFactory backs off. Matching on the exact method source and verifying the bean definition’s factoryBeanName catches the backoff cleanly with zero false negatives.

Honest Trade-Offs: Why Curated Rules Beat Global Environment Scanning

It is tempting to scan every property in Environment and fail whenever any key goes unread. Do not do that. Real production deployments share Helm ConfigMaps, Kubernetes environment variables, and multi-profile YAML files across services; a global unused-key scanner would drown teams in noise within a week and get disabled immediately.

A curated rule list flips that trade-off:

  • Zero false positives by design: If a service does not configure spring.cache.caffeine.* or spring.rsocket.server.fragment-size, the corresponding rule does nothing.
  • Explicit opt-outs for intentional overrides: If a team intentionally supplies a custom kafkaListenerContainerFactory wired properly through ConcurrentKafkaListenerContainerFactoryConfigurer, they acknowledge it once with .ignoringRules("BT-KAFKA-001") right next to an assertion checking live concurrency and Virtual Threads.
  • Gradual rollout: Run boot-truth-starter in WARN mode locally while onboarding legacy services, then flip boot-truth.mode=FAIL in CI and staging once existing drift is resolved.

Why This Matters Even More for AI-Assisted Engineering Teams

As explored in Teaching the Trail, AI coding agents are remarkably productive at generating plausible Spring configuration beans, and remarkably blind to invisible framework coupling.

Ask an agent to add a health-check datasource, customize Kafka retry backoff, or tweak RSocket payload limits, and it will generate syntactically valid Kotlin or Java that compiles on the first try. Without executable startup contracts in CI, neither the agent nor a busy human reviewer sees that one new @Bean silently disabled an entire auto-configuration branch in application.yml.

What to check: Open your main @SpringBootTest integration suite and search for @MockitoBean on DataSource, CacheManager, ConsumerFactory, or security chains. Anywhere a mock replaces infrastructure, your tests are no longer verifying that Spring Boot 4 actually wires your YAML.

What Platform Leads and CTOs Should Put in the Service Template

Rolling these three tiers out across twenty microservices does not require a dedicated platform rewrite. Bake three defaults into your golden-path repository template on Monday:

  • Tier 1 in every internal starter: Require ApplicationContextRunner tests covering both the happy path and missing-dependency / wrong-runtime-type failure paths (Servlet vs. WebFlux, missing Caffeine, auxiliary DataSource).
  • One unmocked InfrastructureContractTest per service: Standardize a 20-line startup contract test checking CacheManager, HikariDataSource, security chains, and messaging factories with zero @MockitoBean overrides.
  • Gradual boot-truth-starter enforcement: Enable boot-truth.mode=WARN locally while onboarding existing services, then enforce boot-truth.mode=FAIL in CI and staging so new pull requests cannot introduce orphaned infrastructure properties.

With those three guardrails in place, that ten-second AI-generated reportingDataSource() pull request never reaches production. It fails in CI in seconds with BT-JDBC-001, names the exact backed-off configuration, and points straight to @Bean(defaultCandidate = false).

In Part 4 of this series, we move one layer deeper: beyond ConditionEvaluationReport into live bean inspection with LivePropertyVerifier. We cover four Spring Boot 4 traps where conditions match or swap cleanly while production still breaks, including Java 21 Virtual Threads erasing pool limits, OTLP/Prometheus falling back to SimpleMeterRegistry, unpooled R2DBC, and custom RabbitMQ listener factories.

You would never send a pointer into thick cover without checking whether it actually holds point before stepping forward. Treat application.yml the same way: verify the beans that boot, and silent configuration bugs lose their hiding place.


Building internal Spring Boot 4 platform starters or tightening CI guardrails across a JVM fleet? A fixed-scope 2-Week Architecture Review audits your system architecture and runtime configuration contracts directly in code, or share one fragile service setup via the contact form for three candid observations within 48 hours.