我是否可以仅在Spring 4中覆盖给定类的@Cacheable KeyGenerator?

时间:2015-10-14 02:30:50

标签: java spring caching spring-cache

我试图覆盖整个班级的KeyGenerator,但不知道是否有一种简单的方法可以做到这一点。

我已经设置了以下配置bean来启用我的缓存:

@Configuration
@EnableCaching(mode=AdviceMode.ASPECTJ)
public class CacheConfig extends CachingConfigurerSupport{
    @Bean(destroyMethod="shutdown")
    public net.sf.ehcache.CacheManager ehCacheManager() {
        CacheConfiguration configCache = new CacheConfiguration();
        veracodeCache.setName("repo");
        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(configCache);
        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }
}

但是,在特定的类中,我想使用不同的密钥生成器。我知道我可以在每个@Cacheable调用中覆盖单个keyGenerator,但无法找到一种方法来覆盖整个类。

例如:

@KeyGenerator("com.domain.MyCustomKeyGenerator")  // <--- anyway to set a different key gen for the entire class?
public class Repo{

   @Cacheable("repo")
   public String getName(int id){
       return "" + id;
   }
}

根据文档,如果我在类型上设置@Cacheable,所有方法都将被缓存(这不是我要找的)。

我的另一个选择当然是在每个方法上指定@Cacheable(value="repo", keyGenerator="com.domain.MyCustomKeyGenerator"),但这是非常多余的,特别是如果我想在多个类上更改默认密钥生成器。

对此有任何支持吗?

1 个答案:

答案 0 :(得分:1)

您可以在班级使用@CacheConfig。它没有启用方法的缓存,只是配置它。

@CacheConfig(keyGenerator="com.domain.MyCustomKeyGenerator") 
public class Repo{

   // your com.domain.MyCustomKeyGenerator will be used here
   @Cacheable("repo")
   public String getName(int id){
       return "" + id;
   }
}