Caching strategies with Spring Cache

David Kumar Jan 2026
2 tabs
package com.example.demo.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("users", "posts");
        cacheManager.setCaffeine(Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(1000)
            .recordStats());
        return cacheManager;
    }
}
2 files · java Explain with highlit

Spring Cache abstraction simplifies caching with annotations. @Cacheable caches method results—subsequent calls with same arguments return cached values. @CachePut always executes methods and updates cache. @CacheEvict removes entries or clears entire caches. Cache providers include Caffeine, Redis, Ehcache, or simple in-memory maps. @EnableCaching activates caching infrastructure. Cache names organize data by domain. Condition and unless parameters provide fine-grained control. KeyGenerator customizes cache keys. Caching dramatically improves performance for expensive operations—database queries, API calls, calculations. Time-to-live (TTL) prevents stale data. Redis enables distributed caching across service instances. Proper caching balances performance gains against data freshness requirements.