It is possible that JCacheCacheConfiguration tries to create a pre-configured cache (using the property spring.cache.cache-names) which is already created. The exception happens during the initialization process when no CacheManager exists in the first. No further checks are performed about the existence of a cache afterwards. But it is possible that caches have been created in the meantime between the check for an instance of CacheManager and calling jCacheCacheManager.createCache.

https://github.com/spring-projects/spring-boot/blob/47516b50c39bd6ea924a1f6720ce6d4a71088651/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java#L83-L90

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.cache.CacheManager]: Factory method 'jCacheCacheManager' threw exception; nested exception is javax.cache.CacheException: A Cache named [myKey] already exists
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
    ... 105 more
Caused by: javax.cache.CacheException: A Cache named [myKey] already exists
    at org.ehcache.jsr107.Eh107CacheManager.createCache(Eh107CacheManager.java:207)
    at org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration.jCacheCacheManager(JCacheCacheConfiguration.java:87)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 106 more

The attached demo project can be used to reproduce the problem by executing of the following commands.

mvn test or mvn test '-Dtest=com.example.demo.ServiceWithCachingTest,com.example.demo.DemoApplicationTests'

demo.zip

see also #31125

Comment From: snicoll

As I've explained in the original issue you've created, this is context pollution due to several contexts being created for your tests while EhCache stores the cache manager in the classloader.

The second test is requesting the underlying EhCache manager and the one of the first test is returned. I've added @DirtiesContext on those tests and things are working as expected.

The exception here is expected as you've requested myKey to be created (with a certain configuration) and such a cache already exists. Trying to change that may impact production scenarios.