首先,您需要在应用程序上下文中创建一个 Ehcache CacheManager 单例,如下所示:
<bean id="myEhCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:my-ehcache.xml"/>
</bean>
这里configLocation
设置为从类路径加载或使用value="/WEB-INF/my-ehcache.xml"
.
在您的控制器中只需注入CacheManager
实例:
@Controller
public class MyUniqueService {
@Resource(name="myEhCacheManager")
private CacheManager cacheManager;
...
}
或者,如果您想走“完全自动布线”的路线,请执行以下操作:
<bean class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="/WEB-INF/ehcache.xml"/>
</bean>
</property>
</bean>
像这样设置你的课程:
@Controller
public class MyUniqueService {
@Autowired
private org.springframework.cache.CacheManager cacheManager;
public org.springframework.cache.Cache getUniqueObjectCache() {
return cacheManager.getCache("uniqueObjectCache");
}
}
uniqueObjectCache
对应于ehcache.xml
缓存定义中的此缓存实例:
<cache name="uniqueObjectCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"
transactionalMode="off"/>
没有办法注入实际的缓存实例,但如上所示,您可以注入缓存管理器并使用它来获取您感兴趣的缓存。