Search code examples
spring-bootspring-cache

Cannot find the cache named xxx for the builder in spring boot application


I have a Spring Boot application where I want to use Spring Boot cache on a repository method. I have specified @EnableCaching annotation in my Spring Boot app.

When I try to use @Cacheable annotation on my repository method, it throws error:

java.lang.IllegalArgumentException: Cannot find cache named 'cache' for Builder[public abstract java.util.Optional
    myRepoMethod(java.lang.String,java.lang.String)] caches=[cache] |key='' | keyGenerator='' | cacheManager='' | cacheResolver='' |condition='' | unless='' | sync='false' at org.springframework.cache.interceptor.AbstractCacheResolver.resolveCaches(AbstractCacheResolver.java:84)
 at org.springframework.cache.interceptor.CacheAspectSupport.getCaches(CacheAspectSupport.java:224)
 at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContext.<init>(CacheAspectSupport.java:669)
 at org.springframework.cache.interceptor.CacheAspectSupport.getOperationContext(CacheAspectSupport.java:237)
 at org.springframework.cache.interceptor.CacheAspectSupport$CacheOperationContexts.<init>(CacheAspectSupport.java:570)
 at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:317)
 at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
 at com.sun.proxy.$Proxy140.findByUserIdAndProduct(Unknown Source) ~[?:?]

I don't know where I have missed out!!

My repository method looks like

    @Cacheable("cache")
    Optional<ModelClass> findByUserIdAndProduct(String userId, String product);

Spring Framework version 5.0.6


Solution

  • because you don't add

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (CacheConstant cacheType : CacheConstant.values()) {
            caffeineCaches.add(new CaffeineCache(cacheType.toString(),
                    Caffeine.newBuilder()
                            .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                            .maximumSize(cacheType.getMaximumSize())
                            .build()));
        }
        cacheManager.setCaches(caffeineCaches);
        return cacheManager;
    }