简体   繁体   中英

Can I override the @Cacheable KeyGenerator for a given class only in Spring 4?

I'm trying to override the KeyGenerator for an entire class, but don't know if there is an easy way to do this.

I've got the following config bean setup to enable my cache:

@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();
    }
}

However, in a specific class, I would like to use a different key generator. I know I can override the individual keyGenerator in each @Cacheable call, but was unable to find a way to override it for the class as a whole.

ex:

@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;
   }
}

According to the docs, if I set @Cacheable on the type, all methods will be cached (which is not what I am looking for).

My other option, of course, is to specify @Cacheable(value="repo", keyGenerator="com.domain.MyCustomKeyGenerator") , on every method, but that is very redundant, esp if I want to change the default key generator on multiple classes.

Is there any support for this?

You can use @CacheConfig at class level. It doesn't enable the cache for the methods, it just configures it.

@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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM