ehcache.xml 是 Ehcache 2.x 的声明式 XML 配置文件,对应 net.sf.ehcache.config.Configuration;Ehcache 3.x 已弃用该格式,改用基于 JSR-107 的新 schema,Spring Boot 2.0+ 默认集成 3.x,旧版配置多为遗留或误配。
ehcache.xml 是 Ehcache 2.x 版本中用于声明式配置缓存行为的 XML 文件,本质是 net.sf.ehcache.config.Configuration 的序列化表达。Ehcache 3.x 已彻底弃用该格式,改用 ehcache.xml(注意:3.x 的同名文件结构完全不同,且基于 JSR-107 和自定义 schema),而 Spring Boot 2.0+ 默认集成的是 Ehcache 3,**如果你在项目里看到旧版 ehcache.xml,大概率是遗留系统或误配了依赖版本**。
检查你的 pom.xml 或 build.gradle:
net.sf.ehcache:ehcache,主配置类是 net.sf.ehcache.CacheManager
org.ehcache:ehcache,主配置类是 org.ehcache.config.Configuration,且不识别旧版 ehcache.xml 的 DTD运行时若抛出 CacheException: Unable to load class net.sf.ehcache.config.Configuration 却又没引入 2.x 依赖,说明你混用了 API 和配置格式。
仅适用于 Ehcache 2.x。典型结构包含 、、 等节点。关键陷阱如下:
中的 path 必须是绝对路径或合法变量,java.io.tmpdir 是占位符,实际会被 JVM 替换 —— 但若磁盘空间不足或权限不对,OverflowToDisk 会静默失效 的 name 必须与代码中 cacheManager.getCache("userCache") 完全一致,大小写敏感timeToIdleSeconds 和 timeToLiveSeconds 同时设为 0 表示永不过期,但 eternal="true" 优先级更高,会覆盖这两个值 时,Ehcache 2.x 会使用内置默认策略(maxElementsInMemory=10000, eternal=false),容易导致内
Spring 2.x–4.x 可通过 ehcache:config 命名空间或 net.sf.ehcache.config.ConfigurationFactory 加载,但强烈建议用 Spring 的抽象层:
org.springframework.cache.ehcache.EhCacheManagerFactoryBean,设置 configLocation 属性指向 classpath 路径,例如:classpath:ehcache.xml
file:/opt/config/ehcache.xml —— 这会导致部署到容器(如 Tomcat)时因路径不可控而失败spring.cache.ehcache.config=classpath:ehcache.xml 指定;但 Boot 2.x+ 默认不支持 Ehcache 2,强行启用需排除 spring-boot-starter-cache 默认实现并手动引入 2.x 依赖,风险高真实项目中,缓存策略的动态调整(比如灰度降级)、多环境差异(dev/staging/prod)很难靠静态 XML 覆盖,更推荐用 Java Config + Builder 模式构造 CacheManager,把过期时间、容量等作为配置项注入。