Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java: Failed to load ApplicationContext in Spring tests

The wrapper hides the real error. Read the deepest Caused by: missing bean, ambiguous bean, unresolved property, database failure, or a stale annotation.

~4 min readJava
#Java#Spring Boot#Testing#Debugging
A Spring context crate collapsed at a cyan startup gate, an amber bean card and a red cause chain beside it

Introduction & Quick Summary

text
java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate .loadContext(DefaultCacheAwareContextLoaderDelegate.java:135) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController' ... Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.order.OrderService' available

Failed to load ApplicationContext is never the actual error. It is the wrapper Spring test support throws when context startup fails, and the answer is the last Caused by in the chain. Read from the bottom up: the deepest cause names the bean, property, or connection that broke.

The five roots behind almost every occurrence:

  • Missing bean — the class sits outside the @SpringBootApplication package tree, so component scanning never sees it.
  • Ambiguous bean — two implementations and no @Primary or @Qualifier.
  • Unresolved property — @Value("${app.key}") with no value in the test profile.
  • Database or broker unavailable — the context tries to open a real connection you did not provide.
  • Deprecated test annotations — @MockBean on a Boot 4 project, or a slice test without the beans its controller needs.
Deepest Caused byRoot causeFix
NoSuchBeanDefinitionExceptionNot scanned / wrong packageMove class, or @Import
NoUniqueBeanDefinitionExceptionTwo candidates@Primary or @Qualifier
Could not resolve placeholderMissing propertyapplication-test.yml or @TestPropertySource
BeanDefinitionOverrideExceptionDuplicate bean nameRename, or enable overriding
BeanCurrentlyInCreationExceptionCircular referenceBreak the cycle, inject lazily
Failed to determine a suitable driver classNo DataSource configTest DB, exclude autoconf
ApplicationContextException: Unable to start web serverPort in use in webEnvironmentUse MOCK or a random port

Core Mechanics, Signatures & Reproducible Setup

@SpringBootTest starts a real application context with your production configuration, then swaps in test beans. Startup runs every @Configuration, every BeanFactoryPostProcessor, every SmartLifecycle, and opens every auto-configured connection pool before a single test method runs. Any failure in that pipeline aborts the context and Spring reports the wrapper.

Each test class configuration is cached by key, so an identical configuration is reused across the suite.

Reproduce a minimal failure:

java
package com.acme.shop; @SpringBootApplication public class ShopApplication {} // in com.acme.services (outside the scan root) @Service public class OrderService {} // in com.acme.shop.web @RestController public class OrderController { private final OrderService orders; public OrderController(OrderService orders) { this.orders = orders; } }
java
@SpringBootTest class OrderControllerTest { @Test void contextLoads() {} }
text
Caused by: NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.services.OrderService' available: expected at least 1 bean

Two correct fixes: move OrderService under com.acme.shop, or widen scanning explicitly.

java
@SpringBootApplication(scanBasePackages = {"com.acme.shop", "com.acme.services"}) public class ShopApplication {}

scanBasePackages is honest but hides layout problems; a shared multi-module project usually wants @Import(SharedConfig.class) in the app or a configuration class in the shared module.

Key Comparison Table

AnnotationContext scopeTypical failure
@SpringBootTestFull application contextAny startup error
@WebMvcTestWeb layer onlyController dependency missing
@DataJpaTestJPA + embedded DBWrong dialect, missing entity
@JsonTestJackson onlyCustom module not registered
@Import(X.class)Adds specific beansDuplicate definitions
Test database strategySetup costMatches production
Embedded H2LowPoorly for Postgres-specific SQL
TestcontainersMediumHigh
Dev databaseLowDrifts, unsafe for CI
@AutoConfigureTestDatabase(replace = NONE)LowAs configured

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: Properties that exist only in production

java
@Component public class JwtVerifier { public JwtVerifier(@Value("${app.jwt.secret}") String secret) {} }
text
Caused by: IllegalArgumentException: Could not resolve placeholder 'app.jwt.secret'

The test profile has no such key. Add src/test/resources/application-test.yml and activate it:

app: jwt: secret: test-secret-not-used-outside-tests
java
@SpringBootTest @ActiveProfiles("test") class JwtVerifierTest { }

Per-test overrides are also valid and keep credentials out of the classpath config:

java
@SpringBootTest(properties = "app.jwt.secret=unit-test-secret") class JwtVerifierTest { }

An inline properties entry wins over application-test.yml, which wins over application.yml.

Case 2: The context opens a real database

text
Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Connection to localhost:5432 refused

Pin the test to an isolated database rather than production:

# src/test/resources/application-test.yml spring: datasource: url: jdbc:tc:postgresql:17:///shop flyway: enabled: true

With Testcontainers and the JDBC URL scheme, the container starts automatically on first connection and stops after the suite. If the test does not need a database at all, exclude the auto-configuration instead of pretending to configure one:

java
@SpringBootTest(excludeAutoConfiguration = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, FlywayAutoConfiguration.class }) class PricingRulesTest { }

Case 3: Two beans of the same type

text
Caused by: NoUniqueBeanDefinitionException: expected single matching bean but found 2: stripeGateway, paypalGateway

Mark the default and qualify the edge case:

java
@Primary @Service class StripeGateway implements PaymentGateway {} @Service @Qualifier("paypal") class PaypalGateway implements PaymentGateway {}
java
public CheckoutService(@Qualifier("paypal") PaymentGateway gateway) { ... }

The test then overrides only what it needs:

java
@MockitoBean PaymentGateway gateway;

@MockitoBean replaced @MockBean (deprecated since Spring Boot 3.4) and lives in org.springframework.test.context.bean.override.mockito. Mixing the two annotations in one project produces confusing bean-resolution failures when both are present.

Case 4: Slice tests and mocked dependencies

java
@WebMvcTest(OrderController.class) class OrderControllerTest { @Autowired MockMvc mvc; }
text
Caused by: NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.order.OrderService'

@WebMvcTest loads controllers and MVC infrastructure only. Provide the collaborators:

java
@WebMvcTest(OrderController.class) class OrderControllerTest { @Autowired MockMvc mvc; @MockitoBean OrderService orders; }

If the controller pulls in a custom @Configuration that drags in JPA, the slice still fails; import only the MVC-related configuration with @Import(WebConfig.class).

Case 5: Circular references

text
Caused by: BeanCurrentlyInCreationException: Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring Boot 2.6 and later forbid cycles by default. The real fix is to break the dependency — extract a third collaborator, or use an event. The escape hatch exists, and it should remain a temporary local change:

properties
spring.main.allow-circular-references=true

@Lazy on one constructor parameter also breaks the cycle, at the cost of a proxy and a delayed failure if the bean is genuinely misconfigured.

Case 6: Web environment and ports

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
text
Caused by: java.net.BindException: Address already in use

DEFINED_PORT binds server.port (8080 by default) and fails when a running app or a parallel Gradle worker holds it. Use RANDOM_PORT and read the port from @LocalServerPort, or MOCK when no real server is needed.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Reporting only the first line. Failed to load ApplicationContext says nothing; copy the full stack or at least the last two Caused by blocks when asking for help.
  • @SpringBootTest everywhere. Full-context tests are the slowest and the most fragile; use slices where the behavior under test is narrow.
  • @Transactional on the test class. It rolls back data but not sequence state, so later tests see IDs starting above 1 and assertions on counts fail intermittently.
  • Profile confusion. @ActiveProfiles("test") does not merge with application.yml; it adds a file, and later files win on conflicting keys.
  • Boot 3.2+ virtual thread and lazy-init defaults. spring.main.lazy-initialization=true changes when a failure appears — often after the context "loads" successfully.
  • Boot 4 test imports. Several test annotations moved packages between 3.x and 4.x; a compile error in a test is worth checking against the version's reference documentation before rewriting the test.

Compare application.yml with application-test.yml using the diff tool when a property resolves in production but not in tests, and validate the YAML with the YAML validator — a tab character where a space belongs makes Spring see a file with no properties at all.

Primary references: Testing Spring Boot Applications covers context caching, slices and test configuration, and the TestContext Framework reference documents context loading and failure semantics.

Official references

primary documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.