Spring Caching — a framework feature that allows you to store method results in cache to improve performance and reduce database or computation load.
🧩 Purpose
When a cached method is called with the same parameters again, Spring returns the cached result instead of executing the method.
Basic Example:
@Service
public class UserService {
@Cacheable("users")
public User getUserById(Long id) {
System.out.println("Fetching from DB...");
return userRepository.findById(id).orElseThrow();
}
}
✅ On first call → runs the method and caches the result.
✅ On next calls with same id
→ returns cached result directly.
🧠 Key Annotations
@EnableCaching
→ activates caching in Spring Boot.@Cacheable
→ caches method result.@CachePut
→ updates cache with new value.@CacheEvict
→ removes data from cache.
Configuration Example:
@SpringBootApplication
@EnableCaching
public class App { }
Spring Boot supports cache providers like ConcurrentMap, Ehcache, Caffeine, Redis, etc.