Default Cache Manager with Spring Boot using @EnableCaching
Solution 1
The Spring Boot starter provides a simple cache provider which stores values in an instance of ConcurrentHashMap. This is the simplest possible thread-safe implementation of the caching mechanism.
If the @EnableCaching
annotation is present in your app, Spring Boot checks dependencies available on your class path and configures an appropriate CacheManager
. Depending on a chosen provider, some additional configuration may be required. You can find all information about configuration in the first link from this answer.
Solution 2
If you want to define explicitly (from any reason) the simplest cache manager (which uses ConcurrentHashMap under the hood), please do:
@Bean
public CacheManager cacheManager() {
return new org.springframework.cache.concurrent.ConcurrentMapCacheManager();
}
PRATHAP S
Passionate about JAVA and related frameworks, Full stack, Technology Enthusiast, Developer, Researcher etc.
Updated on July 25, 2022Comments
-
PRATHAP S almost 2 years
I have implemented caching in my SpringBootApplication as shown below
@SpringBootApplication @EnableCaching public class SampleApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SampleApplication.class); } public static void main(String[] args) { SpringApplication.run(SampleApplication.class, args); }
This is absolutely working fine.
But to implement caching there should be one mandatory CacheManager / Cacheprovider defined. Without defining any cacheManager also my application is working fine.
Is there any default Cache manager defined by Spring ? Spring docs says Spring Boot auto-configures a suitable CacheManager.
So what will be CacheManager used if we do not define it ?
-
PRATHAP S over 7 yearsThanks, so ConcurrentHashMap itself acts as default cache provider if nothing is defined in the application.
-
PRATHAP S over 7 yearsWould this hit the performance of the application with ConcurrentHashMap as provider?
-
Daniel Olszewski over 7 yearsCorrect. ConcurrentHashMap is used by default and is probably sufficient for simple use cases. However, you should look at other providers if more control over cache is required, e.g. max cache capacity or Time-To-Live for particular storage. Caffeine is most likely the simplest providers from the whole list of possibilities.