我想找到一种在ehCache装饰器类中使用Spring依赖关系注入的好方法。 我有我用下面的缓存配置ehcache.xml中:如何在ehCache.xml中声明的ehCache装饰器中传递依赖关系
<cache name="MY_CACHE"
memoryStoreEvictionPolicy="LRU">
<cacheDecoratorFactory class="org.company.MyCacheDecoratorFactory"/>
</cache>
而且我有以下装饰实现:
public class MyCacheDecoratorFactory extends CacheDecoratorFactory implements ApplicationContextAware {
private MyDependency myDependency;
@Override
public Ehcache createDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
final UpdatingSelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(ehcache,
new MyUpdatingCacheEntryFactory());
selfPopulatingCache.setTimeoutMillis(30000);
return selfPopulatingCache;
}
@Override
public Ehcache createDefaultDecoratedEhcache(final Ehcache ehcache, final Properties properties) {
return this.createDecoratedEhcache(ehcache, properties);
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
myDependency = applicationContext.getBean(MyDependency.class);
}
private class MyUpdatingCacheEntryFactory implements UpdatingCacheEntryFactory {
@Override
public void updateEntryValue(final Object key, final Object value) throws Exception {
myDependency.update(key, value);
}
@Override
public Object createEntry(final Object key) throws Exception {
return myDependency.create(key);
}
}
}
所以,我不能用@Autowire直接,因为注入MyDependency修饰器通过我的ehcache.xml中的<cacheDecoratorFactory/>
标签实例化。
所以为了能够使用spring context我实现了ApplicationContextAware
接口。问题是在createDecoratedEhcache()
之后调用setApplicationContext()
方法,并且当MyUpdatingCacheEntryFactory
被实例化时不能设置依赖关系。
我应该如何正确地将我的spring依赖项传递给装饰器?