在谷歌代码上提供的ehcache-spring-annotations库中,可以使用配置选项“create-missing-caches”来动态创建动态缓存(未在ehcache.xml中定义缓存)。纯弹簧ehcache抽象(Spring 3.1.1)中是否有类似的配置?或者还有其他方法可以使用spring ehcache抽象创建动态缓存吗?
答案 0 :(得分:10)
我能够通过扩展org.springframework.cache.ehcache.EhCacheCacheManager并覆盖getCache(String name)方法来实现。以下是代码段:
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;
}
}
如果有人有任何其他更好的方法,请告诉我。