Java 如何在ehCache.xml中声明的ehCache decorator中传递依赖项
我想找到一种在ehCache decorator类中使用Spring依赖项注入的好方法。 我的ehcache.xml具有以下缓存配置:Java 如何在ehCache.xml中声明的ehCache decorator中传递依赖项,java,spring,dependency-injection,ehcache,Java,Spring,Dependency Injection,Ehcache,我想找到一种在ehCache decorator类中使用Spring依赖项注入的好方法。 我的ehcache.xml具有以下缓存配置: <cache name="MY_CACHE" memoryStoreEvictionPolicy="LRU"> <cacheDecoratorFactory class="org.company.MyCacheDecoratorFactory"/> </cache> 因此,我不能使用@Autowire直
<cache name="MY_CACHE"
memoryStoreEvictionPolicy="LRU">
<cacheDecoratorFactory class="org.company.MyCacheDecoratorFactory"/>
</cache>
因此,我不能使用@Autowire直接注入MyDependency,因为decorator是通过我的ehcache.xml中的
标记实例化的
为了能够使用spring上下文,我实现了ApplicationContextAware
接口。问题在于setApplicationContext()
方法是在createdecoratedhcache()
之后调用的,并且在实例化MyUpdateingCacheEntryFactory
时无法设置依赖项
如何将我的spring依赖项正确地传递给装饰器?好的,我可以通过spring以以下方式完成这项工作: 我已经从ehcache.xml中删除了
标记,并添加了一个缓存配置bean,该bean使用缓存管理器在初始化时用decorator替换缓存:
@Component
public class CacheInitConfigurer implements InitializingBean {
@Autowired
private CacheManager cacheManager;
@Autowired
private MyCacheDecoratorFactory decoratorFactory;
@Override
public void afterPropertiesSet() throws Exception {
final Ehcache myCache = cacheManager.getEhcache("MY_CACHE");
cacheManager.replaceCacheWithDecoratedCache(myCache,
decoratorFactory.createDefaultDecoratedEhcache(myCache, null));
}
}
我将我的CacheDecoratorFactory更改如下:
@Component
public class MyCacheDecoratorFactory extends CacheDecoratorFactory {
@Autowired
private MyUpdatingCacheEntryFactory myUpdatingCacheEntryFactory;
@Override
public Ehcache createDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
final SelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(ehcache,
myUpdatingCacheEntryFactory);
selfPopulatingCache.setTimeoutMillis(30 * 1000);
return selfPopulatingCache;
}
@Override
public Ehcache createDefaultDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
return this.createDecoratedEhcache(ehcache, properties);
}
}
它对我有用。如果有人有更好的解决方案,请让我知道
@Component
public class MyCacheDecoratorFactory extends CacheDecoratorFactory {
@Autowired
private MyUpdatingCacheEntryFactory myUpdatingCacheEntryFactory;
@Override
public Ehcache createDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
final SelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(ehcache,
myUpdatingCacheEntryFactory);
selfPopulatingCache.setTimeoutMillis(30 * 1000);
return selfPopulatingCache;
}
@Override
public Ehcache createDefaultDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
return this.createDecoratedEhcache(ehcache, properties);
}
}