Spring Boot仅用jcache实现Hibernate缓存时创建CacheImplementor服务失败
仅使用JCache实现Hibernate二级缓存(无需Ehcache)
问题本质
hibernate-jcache只是Hibernate与JSR-107(JCache)规范的适配层,本身不提供缓存的具体实现。启动报错是因为Hibernate找不到符合JSR-107标准的缓存实现类,无法初始化CacheImplementor服务。添加Ehcache能解决问题,是因为Ehcache是JCache的实现之一——我们只需要替换为其他轻量的JCache实现即可,不需要依赖Ehcache。
解决方案:使用Caffeine JCache(轻量高效的实现)
Caffeine是高性能的Java缓存库,提供了JSR-107规范的实现,体积小、性能优,适合单机场景。
1. 调整依赖
移除Ehcache相关依赖,添加Caffeine的JCache模块:
- Maven:
<dependency> <groupId>com.github.ben-manes.caffeine</groupId> <artifactId>jcache</artifactId> </dependency>
- Gradle:
implementation 'com.github.ben-manes.caffeine:jcache'
2. 配置Hibernate与JCache
在application.properties(或application.yml)中添加Hibernate缓存配置:
# 启用二级缓存 spring.jpa.properties.hibernate.cache.use_second_level_cache=true # 启用查询缓存 spring.jpa.properties.hibernate.cache.use_query_cache=true # 指定JCache作为缓存区域工厂 spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.jcache.JCacheRegionFactory # 指定Caffeine作为JCache提供者(可选,若存在多个JCache实现时需明确) spring.jpa.properties.hibernate.javax.cache.provider=com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider # 选择性启用实体缓存 spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
3. 实体类启用缓存
在需要二级缓存的实体类上添加Hibernate的@Cache注解:
import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "com.yourpackage.User") public class User { // 实体字段与方法 }
4. 可选:自定义缓存规则
如果需要配置缓存过期时间、最大容量等规则,可在classpath下创建cache.xml文件(遵循JCache规范):
<config xmlns="http://www.ehcache.org/v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <!-- 为User实体配置缓存 --> <cache alias="com.yourpackage.User"> <!-- 10分钟过期 --> <expiry> <ttl unit="minutes">10</ttl> </expiry> <!-- 堆内存最多存1000条 --> <heap unit="entries">1000</heap> </cache> </config>
然后在配置中指定该文件路径:
spring.jpa.properties.hibernate.javax.cache.uri=classpath:cache.xml
其他可选JCache实现
如果是分布式场景,可替换为以下符合JSR-107的实现:
- Infinispan:适合分布式缓存,支持集群
- Hazelcast:分布式内存网格,自带JCache实现
内容的提问来源于stack exchange,提问作者kernel
相关产品推荐
相关产品推荐

