Spring Boot: Overriding CacheManager bean makes cache related properties not work

Viewed 2623

I have a Spring Boot 2 application with Redis cache. It worked just fine until I overridden CacheManager bean.

Problem: The following configuration property gets ignored (I can't turn off caching anymore):

spring.cache.type=none

Although according to the documentation it should work.

Question: How to make the spring.cache.type=none work?

There is a workaround like this, but it is far from being a good solution.

More details: Here is how my configuration looks like:

@Configuration
public class CacheConfiguration {
    @Bean
    RedisCacheWriter redisCacheWriter(RedisConnectionFactory connectionFactory) {
        return RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    }

    @Bean
    CacheManager cacheManager(RedisCacheWriter redisCacheWriter) {
        Map<String, RedisCacheConfiguration> ttlConfiguration = ...
        RedisCacheConfiguration defaultTtlConfiguration = ...
        return new RedisCacheManager(
                redisCacheWriter, defaultTtlConfiguration, ttlConfiguration
        );
    }
}
2 Answers

Because you are creating the CacheManager yourself you also have to check spring.cache.type if you want to turn it of.

@Bean
@ConditionalOnExpression("${spring.cache.type} != 'none'")
CacheManager cacheManager(RedisCacheWriter redisCacheWriter) {

A Built in Spring Redis Cache configuration resides in org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration

It has a @Conditional(CacheCondition.class) on it. This CacheCondition checks the value of spring.cache.type property. If its set to "NONE" the whole configuration, including the RedisCacheManager bean won't load at all.

Now as you've created your own configuration where you define the cacheManager by yourself it gets loaded regardless the value of spring.cache.type variable

So you should probably put some conditional value (that will read the spring.cache.type value or your custom condition)

Related