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.

Introduction & Quick Summary
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' availableFailed 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
@SpringBootApplicationpackage tree, so component scanning never sees it. - Ambiguous bean — two implementations and no
@Primaryor@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 —
@MockBeanon a Boot 4 project, or a slice test without the beans its controller needs.
Deepest Caused by | Root cause | Fix |
|---|---|---|
NoSuchBeanDefinitionException | Not scanned / wrong package | Move class, or @Import |
NoUniqueBeanDefinitionException | Two candidates | @Primary or @Qualifier |
Could not resolve placeholder | Missing property | application-test.yml or @TestPropertySource |
BeanDefinitionOverrideException | Duplicate bean name | Rename, or enable overriding |
BeanCurrentlyInCreationException | Circular reference | Break the cycle, inject lazily |
Failed to determine a suitable driver class | No DataSource config | Test DB, exclude autoconf |
ApplicationContextException: Unable to start web server | Port in use in webEnvironment | Use 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:
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; }
}@SpringBootTest
class OrderControllerTest {
@Test void contextLoads() {}
}Caused by: NoSuchBeanDefinitionException: No qualifying bean of type
'com.acme.services.OrderService' available: expected at least 1 beanTwo correct fixes: move OrderService under com.acme.shop, or widen scanning explicitly.
@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
| Annotation | Context scope | Typical failure |
|---|---|---|
@SpringBootTest | Full application context | Any startup error |
@WebMvcTest | Web layer only | Controller dependency missing |
@DataJpaTest | JPA + embedded DB | Wrong dialect, missing entity |
@JsonTest | Jackson only | Custom module not registered |
@Import(X.class) | Adds specific beans | Duplicate definitions |
| Test database strategy | Setup cost | Matches production |
|---|---|---|
| Embedded H2 | Low | Poorly for Postgres-specific SQL |
| Testcontainers | Medium | High |
| Dev database | Low | Drifts, unsafe for CI |
@AutoConfigureTestDatabase(replace = NONE) | Low | As configured |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Properties that exist only in production
@Component
public class JwtVerifier {
public JwtVerifier(@Value("${app.jwt.secret}") String secret) {}
}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@SpringBootTest
@ActiveProfiles("test")
class JwtVerifierTest { }Per-test overrides are also valid and keep credentials out of the classpath config:
@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
Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException:
Failed to initialize pool: Connection to localhost:5432 refusedPin 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: trueWith 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:
@SpringBootTest(excludeAutoConfiguration = {
DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
FlywayAutoConfiguration.class
})
class PricingRulesTest { }Case 3: Two beans of the same type
Caused by: NoUniqueBeanDefinitionException: expected single matching bean
but found 2: stripeGateway, paypalGatewayMark the default and qualify the edge case:
@Primary
@Service
class StripeGateway implements PaymentGateway {}
@Service
@Qualifier("paypal")
class PaypalGateway implements PaymentGateway {}public CheckoutService(@Qualifier("paypal") PaymentGateway gateway) { ... }The test then overrides only what it needs:
@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
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
}Caused by: NoSuchBeanDefinitionException: No qualifying bean of type
'com.acme.order.OrderService'@WebMvcTest loads controllers and MVC infrastructure only. Provide the collaborators:
@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
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:
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
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)Caused by: java.net.BindException: Address already in useDEFINED_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 ApplicationContextsays nothing; copy the full stack or at least the last twoCaused byblocks when asking for help. @SpringBootTesteverywhere. Full-context tests are the slowest and the most fragile; use slices where the behavior under test is narrow.@Transactionalon 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 withapplication.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=truechanges 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 documentationThe Java documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesSpring Boot: No qualifying bean of type available
The context could not satisfy a constructor argument. Scan boundaries, missing stereotypes, ambiguous candidates and test slices are the usual reasons.
Method Scope in Java: How Local Variables Work
Understand how variables behave inside Java methods: local variable boundaries, block scope, parameter scope, shadowing, and lifetime implications.
Java: LazyInitializationException could not initialize proxy
A lazy association was read after the session closed. Fetch it inside the transaction, use a join fetch or entity graph, or map a DTO instead.
Java: HikariPool connection is not available, request timed out
The HikariCP pool ran out of connections for the whole connectionTimeout. Read the counters, find leaks or slow queries, then size the pool.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.