2015-10-14 26 views
0

我想重寫整個類的KeyGenerator,但不知道是否有一種簡單的方法來做到這一點。只能在Spring 4中重寫給定類的@Cacheable KeyGenerator嗎?

我有以下配置豆設置,使我的緩存:

@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

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