@Cacheable helps save time by storing data from slow methods so next time it can give the saved data quickly without running the method again.
@Cacheable for read caching in Spring Boot
@Cacheable(value = "cacheName", key = "#key") public ReturnType methodName(Parameters) { // method code }
value is the name of the cache where data is stored.
key defines how to identify cached data uniquely, often using method parameters.
@Cacheable(value = "books") public Book findBookById(Long id) { // fetch book from database }
@Cacheable(value = "users", key = "#username") public User getUser(String username) { // fetch user details }
@Cacheable(value = "products", key = "#id + '-' + #locale") public Product getProduct(Long id, String locale) { // fetch product with locale }
This service method simulates a slow call by waiting 3 seconds. Using @Cacheable, the first call with an id will take time, but next calls with the same id return instantly from cache.
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class BookService { @Cacheable(value = "books", key = "#id") public String findBookById(Long id) { simulateSlowService(); return "Book " + id; } private void simulateSlowService() { try { Thread.sleep(3000); // simulate delay } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException(e); } } }
Cache keys should uniquely identify the data to avoid wrong data returns.
Cached data stays until cache is cleared or expires, so use for mostly read-only data.
Make sure caching is enabled in your Spring Boot app with @EnableCaching annotation.
@Cacheable stores method results to speed up repeated calls.
Use it for slow or expensive read operations that return the same data for same inputs.
Define cache name and keys clearly to avoid confusion.