SpringBoot整合EhCache 3配置失效:缺失CacheManager Bean求助
你遇到的A component required a bean of type 'org.springframework.cache.CacheManager' that could not be found.错误,本质是SpringBoot无法自动创建EhCache3对应的CacheManager实例,因为缺少必要的依赖、配置文件指定或Bean定义。下面是你遗漏的关键配置:
1. 确保引入正确的依赖
SpringBoot整合EhCache3需要三个核心依赖:Spring缓存启动器、EhCache3本身、JSR-107(javax.cache)API。如果使用Maven,在pom.xml中添加:
<dependencies> <!-- Spring Cache Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- EhCache 3 --> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <!-- JSR-107 API --> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> </dependencies>
2. 在配置文件中指定EhCache配置文件路径
在application.properties或application.yml中添加配置,告诉SpringBoot加载你的ehcache.xml:
# application.properties spring.cache.jcache.config=classpath:ehcache.xml
3. 补充CacheConfig类的Bean定义(自动配置失效时使用)
如果SpringBoot自动配置未生效,可以手动在CacheConfig中定义JCacheCacheManager Bean:
package com.mcd.restaurantmanager.product.config; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.cache.CacheManager; import javax.cache.Caching; import javax.cache.spi.CachingProvider; import java.net.URI; @EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager jCacheManager() { CachingProvider cachingProvider = Caching.getCachingProvider(); return cachingProvider.getCacheManager( getClass().getResource("/ehcache.xml").toURI(), getClass().getClassLoader() ); } @Bean public org.springframework.cache.CacheManager cacheManager(CacheManager jCacheManager) { return new JCacheCacheManager(jCacheManager); } }
4. 修正@Cacheable的缓存名称与参数匹配
你的@Cacheable(value = "id")指定的缓存名称"id",在ehcache.xml中没有对应的<cache>定义,需要改成你配置的缓存别名hierarchyLevelByRestaurantGroupId;同时key表达式要匹配方法参数名称:
@Cacheable(value = "hierarchyLevelByRestaurantGroupId", key = "#id") public String getLevel(BigDecimal id, String somRandom) { // 原有逻辑不变 }
5. 修正缓存监听器的配置问题
你的ehcache.xml中,<cache-template name="default">里引用了不存在的guru.springframework.ehcache.config.CacheLogger,需要替换成你自己的CustomCacheEventLogger:
<cache-template name="default"> <expiry> <ttl unit="seconds">30</ttl> </expiry> <listeners> <listener> <class>com.mcd.restaurantmanager.product.service.CustomCacheEventLogger</class> <event-firing-mode>ASYNCHRONOUS</event-firing-mode> <event-ordering-mode>UNORDERED</event-ordering-mode> <events-to-fire-on>CREATED</events-to-fire-on> <events-to-fire-on>EXPIRED</events-to-fire-on> <events-to-fire-on>EVICTED</events-to-fire-on> </listener> </listeners> <resources> <heap>1000</heap> <offheap unit="MB">10</offheap> <disk persistent="true" unit="MB">20</disk> </resources> </cache-template>
完成以上配置后,重新启动应用即可正常创建CacheManager实例,缓存功能也会生效。
内容的提问来源于stack exchange,提问作者Yashwanth Potu

