Search code examples
spring-bootehcache

How to get information about which Cache Manager is used in a Spring Boot application?


In a Spring Boot application, even when I completely abstain from declaring a specific cache manager, using the @Cacheable annotation will work and serves cached entries. So I assume, that there is at least some simple HashMap caching system at work.

Now, how can I ensure that the intended caching system (e.g. Caffeine or Ehcache) is in place properly and serving my requests and not the cheap included one? Since the caching system is intercepting calls via proxy I quite don't know to set a breakpoint for this.

Is there any way to see which Cache Manager is working currently?


Solution

  • Yes, the default cache mechanism is some HashMap, implemented in ConcurrentMapCacheManager. I suppose the most straightforward means for verifying that you are getting the CacheManager you expect would be something like this.

    Create a service and inject the CachManager into it, and create a PostConstruct method to check that it's the one you want.

    @Service
    public class CacheVerifier {
      private final CacheManager cacheManager;
    
      public CacheVerifier(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
      }
    
      @PostConstruct
      public void verify() {
        assert this.cacheManager instanceof CaffeineCacheManager;
      }
    }