Search code examples
springehcacheehcache-2

How to create cache dynamically with spring ehcache abstraction


In ehcache-spring-annotations library available on google code, a configuration option "create-missing-caches" is available to create dynamic caches (cache not defined in ehcache.xml) on the fly. Is there a similar configuration available in pure spring ehcache abstraction (Spring 3.1.1)? Or is there any other way we can create dynamic caches using spring ehcache abstraction?


Solution

  • I was able to do it by extending org.springframework.cache.ehcache.EhCacheCacheManager and overriding getCache(String name) method. Below is the code snippet:

    public class CustomEhCacheCacheManager extends EhCacheCacheManager {
    
    private static final Logger logger = LoggerFactory
            .getLogger(CustomEhCacheCacheManager.class);
    
    private static final String NO_CACHE_ERROR_MSG = "loadCaches must not return an empty Collection";
    
    @Override
    public void afterPropertiesSet() {
        try {
            super.afterPropertiesSet();
        } catch (IllegalArgumentException e) {
            if (NO_CACHE_ERROR_MSG.equals(e.getMessage())) {
                logger.debug("No cache was defined in ehcache.xml. The error "
                        + "thrown by spring because of this was suppressed.");
            } else {
                throw e;
            }
        }
    }
    
    @Override
    public Cache getCache(String name) {
        Cache cache = super.getCache(name);
        if (cache == null) {
            logger.debug("No cache with name '"
                    + name
                    + "' is defined in encache.xml. Hence creating the cache dynamically...");
            getCacheManager().addCache(name);
            cache = new EhCacheCache(getCacheManager().getCache(name));
            addCache(cache);
            logger.debug("Cache with name '" + name
                    + "' is created dynamically...");
        }
        return cache;
    }
    

    }

    If anyone has any other better approach, please let me know.