如何为Spring Cache设置自定义KeyGenerator?

Vin*_*ers 3 java spring caching ehcache

我正在使用Spring 3.1,我想使用新的缓存功能.然后,我试过:

<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" />
Run Code Online (Sandbox Code Playgroud)

但我没有找到配置我的自定义KeyGenerator的方法.任何的想法?

小智 16

在Spring 3.1 RC1中有一种更好的方法:

<cache:annotation-driven key-generator="myKeyGenerator"/>
<bean id="myKeyGenerator" class="com.abc.MyKeyGenerator" />

import org.springframework.cache.interceptor.KeyGenerator;
public class MyKeyGenerator implements KeyGenerator {

    public Object generate(Object target, Method method, Object... params) {
}}
Run Code Online (Sandbox Code Playgroud)

截至今天,只需从下载弹簧时获得的jar文件中删除org.springframework.context.support-3.1.0.RC1.jar\org\springframework\cache\config\spring-cache-3.1.xsd,它就可以正常工作精细.


Vin*_*ers 5

好的,我只是想办法做到这一点......

<!-- <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" />
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我使用AnnotationDrivenCacheBeanDefinitionParser,我将配置放在我的xml中,它工作正常:)完成!

编辑:

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

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

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

    public CacheManager cacheManager() {
        return new RedisCacheManager(redisCacheTemplate);
    }
}
Run Code Online (Sandbox Code Playgroud)