Я решил эту проблему, поставив все фабрики в пакете, называя их заданным шаблоном и используя reflection
для создания экземпляров, создавая SelfPopulatingCaches
и заменяя их с помощью replaceCacheWithDecoratedCache()
. Вот фрагмент кода:
File configurationFile = new File(EHCACHE_CONFIG_PATH);
Configuration configuration = ConfigurationFactory.parseConfiguration(configurationFile);
CacheManager manager = CacheManager.create(configuration);
for(String cacheName : manager.getCacheNames()){
Cache cache = manager.getCache(cacheName);
try {
Ehcache selfPopulatingCache = createSelfPopulatingCache(cache);
if(selfPopulatingCache != null){
manager.replaceCacheWithDecoratedCache(cache, selfPopulatingCache);
log.info("Factory for cache '" + cache.getName() + "' created.");
}
} catch (Exception e) {
log.error("Error creating self-populating-cache for '" + cache.getName() + "'", e);
}
}
private Ehcache createSelfPopulatingCache(Ehcache cache) throws Exception{
CacheEntryFactory factory = null;
String factoryClassName = "com.myproject.factories." + Utils.capitalize(cache.getName()) + "CacheFactory";
Class factoryClass;
try {
factoryClass = Class.forName(factoryClassName);
} catch (Exception e) {
log.debug("Unable to find factory for cache " + cache.getName());
return null;
}
/**
* factory may need some extra resource (dataSource, parameters)
* organize factories in abstract classes with their constructors
* and ask for factoryClass.getSuperclass() i.e:
*
* if(factoryClass.getSuperclass().equals(AbstractDatabaseCacheFactory.class)){
* Constructor constructor = factoryClass.getConstructor(DataSource.class);
* factory = (CacheEntryFactory)constructor.newInstance(DataSourceListener.getDataSourceMaster());
* }
*
*/
Constructor constructor = factoryClass.getConstructor();
factory = (CacheEntryFactory)constructor.newInstance();
return new SelfPopulatingCache(cache, factory);
}
в пакете com.myproject.factories
вложу классы, как
AccountsCacheFactory.java
EmployersCacheFactory.java
BlogPostsCachFactory.java
Это будет фабрики для accounts
, employers
и blogPosts
областей кэша.