Web与Service项目独立EhCache配置冲突问题求助
Hey Bharathi, let's sort out this EhCache conflict issue once and for all! The root cause here is actually the setShared(true) configuration you've been using—let me break it down and show you the fix.
Why Your Previous Configs Didn't Work
When you set shared=true on EhCacheManagerFactoryBean, EhCache creates a global singleton CacheManager instance across your entire JVM. That means even if you have two different Spring beans with unique names, they're still pointing to the same underlying EhCache CacheManager. So your Web and Service projects were sharing the same cache space, which caused the conflict.
Step-by-Step Fix
1. Update Web Project Configuration
The key change here is setting shared=false to force a separate CacheManager instance for the Web project. Also, we'll use explicit bean names to avoid any Spring bean collisions:
@Bean(name = "webEhCacheCacheManager") public EhCacheCacheManager ehCacheCacheManager() { net.sf.ehcache.CacheManager cacheManager = ehCacheManagerFactoryBean().getObject(); return new EhCacheCacheManager(cacheManager); } @Bean(name = "webEhCacheManagerFactory") public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean(); cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); // Disable shared mode to create an independent CacheManager cacheManagerFactoryBean.setShared(false); return cacheManagerFactoryBean; }
2. Update Service Project Configuration
Do the same for the Service project—disable shared mode and ensure the CacheManager is fully independent:
@Bean(name = "serviceCacheManager") public IServiceCacheManager cacheManager() { return new ServiceCacheManager(); } public class ServiceCacheManager extends /* Your parent class here */ { public ServiceCacheManager() { EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean(); factory.setConfigLocation(new ClassPathResource("service-ehcache.xml")); // Critical: Disable shared mode for independent cache factory.setShared(false); factory.afterPropertiesSet(); setCacheManager(factory.getObject()); } public ServiceCacheManager(net.sf.ehcache.CacheManager cacheManager) { super(cacheManager); } }
Additional Tips to Avoid Future Issues
- Distinct Cache Names (Optional but Recommended): Even though the CacheManagers are independent, giving caches unique names across your
ehcache.xmlandservice-ehcache.xmlwill make debugging easier later on. - Consistent EhCache Versions: Make sure both projects use the same version of EhCache to avoid unexpected compatibility bugs.
- Verify Independence: Test by storing a key with the same name in both projects—if each returns its own value, you've successfully separated the caches.
内容的提问来源于stack exchange,提问作者Bharathiraja S

