Grails 4.0.10中Hibernate二级缓存启动失败:RegionFactory创建异常
解决Grails 4.0.10配置Hibernate二级缓存时的ClassNotFoundException问题
问题核心
报错的本质是无法加载org.hibernate.cache.ehcache.EhCacheRegionFactory类,根源在于配置冲突、依赖引入不规范,以及缺少EhCache的核心配置文件。
分步修复方案
1. 修正依赖配置
Grails 4.x基于Gradle 6+,compile指令已被废弃,改用implementation确保依赖被正确加入运行时classpath:
implementation "org.hibernate:hibernate-ehcache:5.4.0.Final"
执行./gradlew clean build重新拉取依赖,避免缓存导致的依赖缺失。
2. 清理application.yml中的冲突配置
初始配置同时存在旧版Hibernate的provider_class和新版的region.factory_class,二者冲突。删除冗余项,保留标准配置:
hibernate: jdbc: time_zone: US/Mountain cache: queries: false use_second_level_cache: true use_query_cache: true region: factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
注意:不要给类名加单引号,YAML会自动识别字符串类型。
3. 添加EhCache核心配置文件
在src/main/resources目录下创建ehcache.xml,提供基础缓存规则(无此文件EhCache无法初始化),示例配置:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" dynamicConfig="true"> <!-- 默认缓存规则 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"/> <!-- 可自定义实体缓存区域,例如针对业务Domain类 --> <cache name="com.yourpackage.YourDomain" maxElementsInMemory="5000" timeToIdleSeconds="300" timeToLiveSeconds="600"/> </ehcache>
4. 排查依赖冲突
执行./gradlew dependencies查看依赖树,检查是否存在不同版本的EhCache或Hibernate依赖。如果有冲突,排除不兼容的依赖,例如:
implementation("org.hibernate:hibernate-ehcache:5.4.0.Final") { exclude group: 'net.sf.ehcache', module: 'ehcache' } // 手动引入兼容版本的EhCache核心包 implementation "net.sf.ehcache:ehcache:2.10.6"
验证配置(可选)
在需要启用二级缓存的Domain类上添加注解,验证缓存生效:
class YourDomain { String name static mapping = { cache true // 开启该类的二级缓存 } }
内容的提问来源于stack exchange,提问作者kofhearts
相关产品推荐
相关产品推荐

