Cache configuration helps your app remember data so it can work faster next time. It saves time by not repeating slow tasks.
Cache configuration in Spring Boot
@EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("items"); } }
@EnableCaching turns on caching in your Spring Boot app.
CacheManager defines where and how cache is stored.
@EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("books", "authors"); } }
@EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { SimpleCacheManager manager = new SimpleCacheManager(); manager.setCaches(List.of(new ConcurrentMapCache("users"))); return manager; } }
This program sets up a cache named 'greetings'. The GreetingService method getGreeting simulates a slow call by waiting 2 seconds. The first call caches the result. The second call returns the cached greeting immediately, making it faster.
import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Service; import java.util.List; @EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("greetings"); } } @Service class GreetingService { @Cacheable("greetings") public String getGreeting(String name) { try { Thread.sleep(2000); // simulate slow method } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Hello, " + name + "!"; } } // Usage example (e.g., in a Spring context with @Autowired GreetingService service): // System.out.println(service.getGreeting("Alice")); // takes 2 seconds first time // System.out.println(service.getGreeting("Alice")); // returns instantly from cache
Cache names must match between configuration and @Cacheable annotations.
Use caching only for data that does not change often or can be stale briefly.
Spring Boot supports many cache types like Redis, Ehcache, and simple memory caches.
Cache configuration speeds up apps by storing data temporarily.
Use @EnableCaching and define a CacheManager bean to set up caching.
Mark methods with @Cacheable to save their results automatically.