Introduction
Caching helps your app work faster by saving results of slow tasks. It avoids doing the same work again and again.
Caching helps your app work faster by saving results of slow tasks. It avoids doing the same work again and again.
@Cacheable("cacheName")
public ReturnType methodName(Parameters) {
// method logic
}@Cacheable("books") public Book findBookById(Long id) { // fetch book from database }
@Cacheable("prices")
public double calculatePrice(Product product) {
// heavy price calculation
}This service method simulates a slow operation by waiting 3 seconds. Using @Cacheable caches the result so repeated calls with the same key are fast.
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class DataService { @Cacheable("dataCache") public String getData(String key) { try { Thread.sleep(3000); // simulate slow call } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Data for " + key; } } // Usage example in a Spring Boot app: // Calling getData("test") first time takes 3 seconds. // Calling getData("test") again returns instantly from cache.
Remember to enable caching in your Spring Boot app with @EnableCaching annotation.
Caches store data in memory by default, so be mindful of memory limits.
Cache keys are based on method parameters by default.
Caching saves time by reusing previous results.
Use @Cacheable on methods that do slow or repeated work.
Enable caching in your app to see performance improvements.
@Cacheable("books")
public Book findBook(String id) {
simulateSlowService();
return new Book(id, "Title");
}findBook("123") is called twice?@Cacheable("users")
public User getUser(int id) {
return userRepository.findById(id).get();
}
// Missing @EnableCaching annotation in main classPass the test and this pattern moves unknown