You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot Java配置Ehcache报Cannot find cache name异常

问题根因

报错的核心原因是配置逻辑错误:你在配置类构造方法里直接创建了Ehcache原生的CacheManager实例,但没有将其注册为Spring缓存抽象认可的CacheManager Bean。Spring的@Cacheable注解拦截逻辑完全感知不到你手动创建的Ehcache实例和其中定义的myCache缓存,自然会抛出找不到对应缓存的异常。

修复方案

你需要用Spring提供的Ehcache适配器,把手动创建的Ehcache管理器包装成Spring容器能识别的Bean,修正后的配置类代码如下:

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.interceptor.SimpleKey;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public org.ehcache.CacheManager ehcacheNativeManager() {
        var cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .withCache("myCache",
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(
                                SimpleKey.class,
                                String.class,
                                ResourcePoolsBuilder.heap(10)
                        )
                )
                .build();
        cacheManager.init();
        return cacheManager;
    }

    @Bean
    public CacheManager springCacheManager(org.ehcache.CacheManager ehcacheNativeManager) {
        return new EhCacheCacheManager(ehcacheNativeManager);
    }
}
配置说明
  • 不要在配置类构造方法中初始化Ehcache核心实例:构造方法执行时Spring Bean生命周期还未完成,容易出现初始化顺序冲突,所有缓存实例统一通过@Bean方法注册即可
  • 未手动指定key的@Cacheable注解默认使用SimpleKey作为缓存key类型,你之前配置的key类型匹配,不需要额外调整
  • 后续需要新增缓存时,直接在ehcacheNativeManager的Bean定义中追加.withCache()配置即可,和XML配置的能力完全对等

之前XML配置能正常运行,是因为Spring Boot的Ehcache自动配置类会自动读取XML路径下的配置文件,自动完成Ehcache实例创建、Spring适配器注册的全流程。改为Java代码手动配置后,这层适配逻辑需要自己实现,自动配置不会触发。

内容的提问来源于stack exchange,提问作者Jenga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 22:33:39