4

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?

Eduard Wirch
  • 9,785
  • 9
  • 61
  • 73
Sudhir
  • 1,339
  • 2
  • 15
  • 36

1 Answers1

11

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.

Sudhir
  • 1,339
  • 2
  • 15
  • 36
  • 1
    If you don't care about the logging, the getCache() method can more simply be written as: `getCacheManager().addCacheIfAbsent(name); return super.getCache(name);` – engfer Feb 11 '14 at 17:22
  • getCacheManager().cacheExists(name) returns true, even if that cache name doesn't exist. –  Jan 29 '15 at 14:11