Spring项目切换SimpleCacheManager为PersistentCacheManager找不到myCache报错
问题排查与解决步骤
第一步:确认引入Spring对Ehcache3的适配依赖
你当前直接返回Ehcache原生PersistentCacheManager会导致Spring缓存抽象无法识别,必须引入适配层依赖:Spring Boot 3+/Spring 6+环境引入org.springframework.boot:spring-boot-starter-cache、org.ehcache:ehcache、org.springframework.cache:spring-cache-support即可。第二步:修改CacheManager Bean配置,用Spring适配类包装原生Ehcache管理器
Spring的缓存抽象只识别实现了org.springframework.cache.CacheManager接口的Bean,原生Ehcache管理器没有实现该接口,修改配置如下:
import org.springframework.cache.ehcache3.Ehcache3CacheManager; // 其余import省略 @Bean public org.springframework.cache.CacheManager cacheManager() { // 创建原生持久化缓存管理器 PersistentCacheManager nativeCacheManager = CacheManagerBuilder.newCacheManagerBuilder() .with(CacheManagerBuilder.persistence(new File(storagePath, "myData"))) .withCache("myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, NotificationListResponse.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MemoryUnit.MB, true)) ) .build(); nativeCacheManager.init(true); // 包装为Spring可识别的缓存管理器 return new Ehcache3CacheManager(nativeCacheManager); }
第三步:验证缓存配置匹配性
- 确认
@Cacheable标注的方法返回值类型和缓存定义的NotificationListResponse完全一致,无类型不匹配或泛型擦除问题 - 确认
storagePath目录存在,且应用进程拥有该目录的读写权限,避免Ehcache持久化存储初始化失败导致缓存未注册
- 确认
第四步:可选:显式指定缓存管理器
如果项目中存在多个CacheManager实例,需要在@Cacheable注解中显式指定对应的缓存管理器Bean名称:
@Cacheable(value = "myCache", cacheManager = "cacheManager", key = "'myCache' + #listType", unless = "#result.getMyList().size() == 0")
- 第五步:检查版本兼容性
确认Spring/Spring Boot版本和Ehcache3版本兼容,Spring Boot 3.x对应Ehcache 3.10+版本,避免版本不兼容导致适配失败。
内容的提问来源于stack exchange,提问作者Paloma Schkrab
相关产品推荐
相关产品推荐

