2017-02-13 5 views

답변

0

를 사용하여 selfPopulatingCaches을 대체 할당 할 수 CacheEntryFactories 감지 CacheManager 인스턴스를 생성 나는이 문제를 해결했다. 주어진 패턴으로 이름을 지정하고 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에 나는 accounts, employersblogPosts 캐시 지역에 대한 공장됩니다

AccountsCacheFactory.java 
EmployersCacheFactory.java 
BlogPostsCachFactory.java 

같은 클래스를 넣어 것입니다.