Spring Boot中能否通过application.properties配置Ehcache作为Hibernate二级缓存?
如何通过application.properties配置Hibernate二级缓存(Ehcache)
前提说明
如果你在Spring Boot项目中想完全用application.properties替代Ehcache的XML配置,可结合Spring缓存自动配置与Hibernate缓存设置实现,具体步骤如下:
1. 确认依赖配置
确保项目引入正确依赖(以Maven为例):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> </dependency>
2. 配置Hibernate二级缓存基础参数
在application.properties中启用二级缓存并指定Ehcache作为实现:
# 启用Hibernate二级缓存 spring.jpa.properties.hibernate.cache.use_second_level_cache=true # 按需启用查询缓存 spring.jpa.properties.hibernate.cache.use_query_cache=true # 指定Ehcache为缓存区域工厂 spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory # 关闭默认Ehcache XML配置加载,避免冲突 spring.jpa.properties.hibernate.cache.provider_configuration_file_resource_path=none
3. 配置默认缓存的具体参数
对应你原XML中的defaultCache配置,直接在application.properties中定义:
# 指定缓存类型为Ehcache spring.cache.type=ehcache # 定义默认缓存名称 spring.cache.cache-names=defaultCache # 配置默认缓存参数 spring.cache.ehcache.cache.defaultCache.max-elements-in-memory=100 spring.cache.ehcache.cache.defaultCache.time-to-idle-seconds=20000 spring.cache.ehcache.cache.defaultCache.time-to-live-seconds=3 spring.cache.ehcache.cache.defaultCache.overflow-to-disk=false spring.cache.ehcache.cache.defaultCache.disk-persistent=false spring.cache.ehcache.cache.defaultCache.memory-store-eviction-policy=LRU
4. 实体类绑定缓存
在需要启用二级缓存的实体类上添加Hibernate的@Cache注解,指定使用上述缓存区域:
@Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "defaultCache") public class YourEntity { // 实体类字段与方法 }
关于占位符不生效的说明
Ehcache原生XML配置不支持Spring的${...}占位符解析,除非通过Spring的EhCacheFactoryBean加载XML(此时Spring会自动解析占位符)。但如果想完全用application.properties管理配置,直接使用上述步骤即可,无需依赖XML文件。
内容的提问来源于stack exchange,提问作者Kapil khandelwal
相关产品推荐
相关产品推荐

