如何为Spring Cache设置自定义KeyGenerator? [英] How can I set a custom KeyGenerator for Spring Cache?

查看:344
本文介绍了如何为Spring Cache设置自定义KeyGenerator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring 3.1,我想使用新的缓存功能。然后,我尝试了:

I'm using Spring 3.1 and I want to use the new cache features. Then, I tried:

<cache:annotation-driven />

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
    p:cache-manager-ref="ehcache" />

<!-- Ehcache library setup -->
<bean id="ehcache"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
    p:config-location="classpath:ehcache.xml" />

但我找不到配置自定义KeyGenerator的方法。有什么想法?

But I didn't find the way to configure my custom KeyGenerator. Any idea?

推荐答案

好的,我找到了办法做到这一点......

Ok, I just find a way to do this...

<!-- <cache:annotation-driven /> -->

<bean id="annotationCacheOperationSource"
    class="org.springframework.cache.annotation.AnnotationCacheOperationSource" />

<bean id="cacheInterceptor" class="org.springframework.cache.interceptor.CacheInterceptor"
    p:cacheDefinitionSources-ref="annotationCacheOperationSource"
    p:cacheManager-ref="cacheManager" p:keyGenerator-ref="keyGenerator" />

<bean id="beanFactoryCacheOperationSourceAdvisor"
    class="org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor"
    p:adviceBeanName="cacheInterceptor" p:cacheDefinitionSource-ref="annotationCacheOperationSource" />

<bean id="keyGenerator"
    class="my.company.cache.ReflectionBasedKeyGenerator" />

如您所见,我使用AnnotationDrivenCacheBeanDefinitionParser,我将配置放在我的xml中,它可以工作:)完成!

As you can see, I use the AnnotationDrivenCacheBeanDefinitionParser, I put the configuration in my xml, and it works :) Done!

编辑:

对于Spring> 3.2,您可以使用简单的Java类配置实现CachingConfigurer:

For Spring > 3.2, you can use a simple Java class configuration implementing CachingConfigurer:

@EnableCaching(mode = AdviceMode.ASPECTJ)
public class CacheConfig implements CachingConfigurer {

    public KeyGenerator keyGenerator() {
        return new ReflectionBasedKeyGenerator();
    }

    public CacheManager cacheManager() {
        return new RedisCacheManager(redisCacheTemplate);
    }
}

这篇关于如何为Spring Cache设置自定义KeyGenerator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆