在xml中使ConcurrentMapCacheManager事务感知



我必须在这个应用程序中使用XML配置和注释。在我的配置中,我定义了一个缓存管理器:

<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.concurrent.ConcurrentMapCacheManager"/>

我有几个为缓存和事务注释的服务方法。

@Cacheable("userCache")
@Transactional(readOnly = true)
User getByUsername( String username );

@CacheEvict(value = "userCache", allEntries = true),
@Transactional
void save(List<User> users);

我需要让ConcurrentMapCacheManager事务知道。我在文章Spring缓存注释中看到了一些例子:一些提示&显示如何通过@Bean方法将缓存管理器封装在事务感知代理中的技巧,但无法使用XML实现这一点。

以下是我解决这个问题的方法。在我的上下文中,我声明了一个自定义缓存管理器

<cache:annotation-driven />
<bean id="cacheManager" class="com.sample.cache.TransactionAwareCacheManager"/>

自定义缓存管理器是一个感知事务的代理,封装实际的缓存管理器。

package com.sample.cache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.transaction.TransactionAwareCacheManagerProxy;
public class TransactionAwareCacheManager extends TransactionAwareCacheManagerProxy {
public TransactionAwareCacheManager() {
super(new ConcurrentMapCacheManager());
}
}

最新更新