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

升级Spring Boot 3.0.2后EHCache配置失效,导入报错求助

Spring Boot 3.0.2 升级后 EhCache 配置修复方案

问题根源

Spring Boot 3 基于 Spring Framework 6,该版本已移除对 Ehcache 2.x 的原生支持,org.springframework.cache.ehcache 包下的所有类均被删除,这就是你遇到导入无法解析异常的原因。


1. 调整 Gradle 依赖配置

移除旧的 Ehcache 2.x 依赖,替换为 Ehcache 3 的 JCache 实现(Spring Boot 3 官方推荐通过 JCache 集成 Ehcache 3):

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.2'
    id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

group = 'com.image'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {  
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    // 替换为 Ehcache 3 的 JCache 依赖
    implementation 'org.ehcache:ehcache:3.10.8'
}

2. 简化缓存配置(利用 Spring Boot 自动配置)

Spring Boot 3 对 JCache 提供自动配置支持,无需手动创建旧版的缓存管理器 Bean,按以下步骤配置即可:

2.1 添加 Ehcache 3 配置文件

在 src/main/resources 下创建 ehcache.xml,定义缓存规则(对应你原配置的参数):

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.ehcache.org/v3"
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd">

    <cache alias="yourCacheName">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.Object</value-type>
        <expiry>
            <tti unit="seconds">3600</tti> <!-- 空闲超时时间(对应原 timeToIdleSeconds) -->
            <ttl unit="seconds">86400</ttl> <!-- 存活超时时间(对应原 timeToLiveSeconds) -->
        </expiry>
        <resources>
            <heap unit="entries">10000</heap> <!-- 堆内存最大缓存条目(对应原 maxEntriesLocalHeap) -->
        </resources>
        <eviction-adapter>
            <lru/> <!-- LRU 淘汰策略(对应原 memoryStoreEvictionPolicy) -->
        </eviction-adapter>
    </cache>

</config>

2.2 开启缓存注解支持

在启动类或配置类上添加 @EnableCaching 注解即可,无需手动编写缓存管理器 Bean:

package com.image.cache.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;    

@Configuration
@EnableCaching
public class CacheConfig {
    // 空配置类即可,Spring Boot 会自动加载 JCache 配置
}

2.3 指定缓存类型

在 application.properties 中配置缓存类型及配置文件路径:

spring.cache.type=jcache
spring.cache.jcache.config=classpath:ehcache.xml

3. 验证缓存使用

在需要缓存的方法上使用 @Cacheable 注解,指定缓存名称即可:

@Cacheable(value = "yourCacheName")
public Object getCachedData(String key) {
    // 业务逻辑代码,返回需要缓存的数据
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:47:12