我有一个自定义密钥生成器,只有在我使用注释"keyGenerator"
中的属性时才会调用它。@Cachehable
创建它的我的配置类作为 gradle 依赖项被拉入(并被加载并创建了我的密钥生成器。)。
配置:
@EnableCaching
@Configuration
public class CacheKeyConfig extends CachingConfigurerSupport
{
private static final Logger LOGGER = LoggerFactory.getLogger( CacheKeyConfig.class );
@Bean
@Primary
public KeyGenerator keyGenerator(@Autowired( required = false ) List<CacheKeyGenerator> keyGenerators)
{
return new DynamicCacheKeyGenerator( keyGenerators );
}
}
我传递给它的列表是一组密钥生成器,开发人员可以创建(作为 bean),可用于特定的缓存解析器/管理器。因此,它允许为 MemCache、Redis 或 EhCache 使用不同的密钥生成器(如果您要在一个项目中使用多个)。但这可以是一个空列表。
密钥生成器:
public class DynamicCacheKeyGenerator implements KeyGenerator
{
private static Logger LOGGER = LoggerFactory.getLogger( DynamicCacheKeyGenerator.class );
private Map<Method, CacheKeyGenerator> keyGenerators = new HashMap<>();
@Autowired
public DynamicCacheKeyGenerator(List<CacheKeyGenerator> keyGenerators)
{
//Map the generators to the resolvers
mapGeneratorsToResolvers( CacheResolverFinder.getMethodCacheResolvers(), keyGenerators );
}
//...elided...
@Override
public Object generate(Object target, Method method, Object... params)
{
//Try to get the cache key handler for this method
CacheKeyGenerator generator = keyGenerators.get( method );
//...elided...
return generator.generate( target, method, params );
}
}
以下将永远不会使用我的密钥生成器:
@Cacheable( value = "MyCache", cacheResolver = "MyResolver" )
但以下确实使用它:
@Cacheable( value = "MyCache", cacheResolver = "MyResolver", keyGenerator = "keyGenerator" )
我如何让我的成为默认值?
编辑:即使更改为以下内容也不会使用我的密钥生成器:
@EnableCaching
@Configuration
public class CacheKeyConfig extends CachingConfigurerSupport
{
private static final Logger LOGGER = LoggerFactory.getLogger( CacheKeyConfig.class );
@Autowired
private List<CacheKeyGenerator> myKeyGenerators;
//This DOES get called
@Override
public KeyGenerator keyGenerator()
{
return new DynamicCacheKeyGenerator( myKeyGenerators );
}
}