我想找到一種在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依賴項傳遞給裝飾器?