Sergiy
Sergiy

Reputation: 2041

Spring Boot 2.0 fails to work with Caffeine as cache provider

I create Spring Boot 2.0 Starter project using web and cache dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Then I updated Spring bootstrap class to test REST services caching:

@SpringBootApplication
@EnableCaching
@RestController
@RequestMapping
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping
    @Cacheable("hello")
    public String hello() {
        return "1";
    }
}

and specified simple cache provider in application.properties:

spring.cache.type=simple

Everything worked as expected. Then I added Caffeine dependency and changed cache type:

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

spring.cache.type=caffeine

After that application failed to start with exception:

Caused by: java.lang.IllegalArgumentException: No cache manager could be auto-configured, check your configuration (caching type is 'CAFFEINE') at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerValidator.checkHasCacheManager(CacheAutoConfiguration.java:151) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]

I tried to supply cache names in application.properties but it didn't help.

spring.cache.cache-names=hello

Please advise.

Upvotes: 3

Views: 7828

Answers (2)

YuKitAs
YuKitAs

Reputation: 96

The same happened to me, and I also have Redis installed. spring.cache.type=caffeine wouldn't work, as well as spring.cache.caffeine.spec. It seemed that it tried to use the Redis cache provider, which has precedence over Caffeine, unless you disable Redis auto-configuration explicitly. Otherwise you have to configure Caffeine manually like:

@Configuration
public class CaffeineCacheConfiguration {
    @Bean
    public CacheManager cacheManager() {
        CaffeineCache helloCache = new CaffeineCache("hello",
                Caffeine.newBuilder().expireAfterAccess(60, TimeUnit.SECONDS).build());
        SimpleCacheManager manager = new SimpleCacheManager();
        manager.setCaches(Collections.singletonList(helloCache));
        return manager;
    }
}

Upvotes: 1

Abhinav Agarwal
Abhinav Agarwal

Reputation: 224

Add the following dependency:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>5.0.8.RELEASE</version>
</dependency>

Upvotes: 4

Related Questions