DKS
DKS

Reputation: 315

java.lang.IllegalArgumentException: Cannot find cache named ... for Builder

I am getting error while implementing Caching (using Caffeine Cache) in an existing project.

Same code works fine for example application. I know similar questions has already been asked but neither worked for me. I have implemented using this example: https://www.javadevjournal.com/spring-boot/spring-boot-with-caffeine-cache/

Below are the code snippet: EventListner Class:

MyEventListener.java:

 @Slf4j
    @Component
    @AllArgsConstructor
    class MyEventListener {
         @Autowired
         private final MySecurityServiceClient mySecurityServiceClient;
.
....some code
.
ResponseEntity<TokenResponse> tokenResponseResponseEntity =mySecurityServiceClient.getUserToken();
}

MySecurityServiceClient.java:

public interface MySecurityServiceClient {
    public ResponseEntity getUserToken();

}

Interface implementing class DefaultMySecurityServiceClient.java:

    @Component
    @Slf4j
    @AllArgsConstructor
    public class DefaultMySecurityServiceClient  implements MySecurityServiceClient{
     .
     ...some code
     .
    @Override
    @Cacheable("userToken")
    public ResponseEntity getUserToken() {
    .
    .
    .
 return responseEntity;
}

}

application.properties

spring.cache.cache-names=userToken
spring.cache.caffeine.spec=expireAfterWrite=120s

Also, I am using Caffeine Cache Version = 2.8.5

Spring Boot version = 2.3.5.RELEASE

Error:

java.lang.IllegalArgumentException: Cannot find cache named 'userToken' for Builder[public org.springframework.http.ResponseEntity xx.xx.xx.xx.xx.DefaultMySecurityServiceClient.getUserToken()] caches=[userToken] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'

Upvotes: 2

Views: 2245

Answers (1)

Aniket Ghare
Aniket Ghare

Reputation: 1

Create a new configuration class to configure a cache provider to manage the cache using ConcurrentMapCacheManager, which uses an in-memory map for caching.

Add the following bean to your application:

@Configuration
@EnableCaching
public class CacheConfiguration {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("userToken");
    }
}

I hope it works.

Upvotes: 0

Related Questions