Understanding when and how many Spring ApplicationContexts are created in your test suite allows you to optimize
build times by leveraging Spring TestContext's context caching feature, which reuses already started contexts.
Generated at: 2026-07-23 14:17:30
โถ
Understanding Spring TestContext Context Caching
Click to learn about Spring TestContext context caching principles and optimization tips
Spring Test Framework provides context caching to improve test performance by reusing ApplicationContext instances across multiple test classes when they share the same configuration.
Every Spring test needs an ApplicationContext - and starting one from scratch is expensive.Spring X-rays the test setup and collects every customization point that shapes the context.The result is a MergedContextConfiguration - its hashCode becomes the cache key.Same key already in the cache? The existing context is reused instantly.One tiny difference creates a new key - and a slow, brand-new context.Spring Test Profiler shows you how many contexts your suite creates - and why.
How Context Caching Works
Spring generates a cache key based on:
Context Loader - The class responsible for loading the context
Locations & Classes - Configuration files/classes specified in @ContextConfiguration
Active Profiles - Profiles activated via @ActiveProfiles
Property Sources - Test property sources from @TestPropertySource
Context Customizers - Customizers from test slices like @WebMvcTest
๐ฏ Cache Hit
When a test class has the same exact configuration as a previous test, Spring reuses the existing ApplicationContext. This results in faster test execution.
๐ Cache Miss
When a test class has a different configuration, Spring creates a new ApplicationContext. This takes more time but ensures test isolation.
Optimization Tips
Group similar tests: Use the same @ContextConfiguration across related test classes
Minimize @DirtiesContext: Avoid marking contexts as dirty unless absolutely necessary
Use test slices: @WebMvcTest, @DataJpaTest create focused, cacheable contexts
Consolidate profiles: Use consistent @ActiveProfiles across test classes
๐ Learn More
For detailed information about Spring Test context caching: