Profile photo for Jeet Singh Parmar

I will give you the easiest way to enable second level cache in Spring Boot

Before continue there are so many types of second level cahes are available

1 - JCache

2 - Ehcache

3 - Gvava Cache

4 - Hazelcast Cache

5 - Caffeine Cache

and many more. each and every cache has there own implementations.

But there is one good thing about Spring Boot, to enable second level cache. If you don’t want to use any of caches whatever i mentioned on top. then follow below steps and you can enable second level cache very easily -

Step 1 - add below dependency in pom.xml

  1. <dependency> 
  2. <groupId>org.springframework.boot</groupId> 
  3. <artifactId>spring-boot-starter-cache</artifactId> 
  4. </dependency> 

Step 2 - create one config class and add below code

  1. import java.util.ArrayList; 
  2. import java.util.List; 
  3. import org.springframework.cache.Cache; 
  4. import org.springframework.cache.CacheManager; 
  5. import org.springframework.cache.annotation.EnableCaching; 
  6. import org.springframework.cache.concurrent.ConcurrentMapCache; 
  7. import org.springframework.cache.support.SimpleCacheManager; 
  8. import org.springframework.context.annotation.Bean; 
  9. import org.springframework.context.annotation.ComponentScan; 
  10. import org.springframework.context.annotation.Configuration; 
  11.  
  12. @Configuration 
  13. @EnableCaching 
  14. public class CacheConfig { 
  15. @Bean 
  16. public CacheManager cacheManager() { 
  17. SimpleCacheManager cacheManager = new SimpleCacheManager(); 
  18. List<Cache> cacheList = new ArrayList<Cache>(); 
  19. cacheList.add(new ConcurrentMapCache("cache1")); 
  20. cacheList.add(new ConcurrentMapCache("cache2")); 
  21. //so like that you can create as many as you want 
  22. cacheManager.setCaches(cacheList); 
  23. return cacheManager; 
  24. } 
  25. } 

Step 3 - Use wherever you want

  1. @Override 
  2. @Cacheable(value = "cache1") 
  3. public List<SomeObject> someList() { 
  4. return repository.findAll(); 
  5. } 

that’s it and works perfectly.

if you want to some more proper way then watch below video that is about Cache

Thanks for reading :)

View 1 other answer to this question
About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025