首页 文章

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

提问于
浏览
0

我试图覆盖整个类的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 回答

  • 1

    您可以在 class 使用 @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;
       }
    }
    

相关问题