import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class BookService { @Cacheable("books") public String findBook(String isbn) { System.out.println("Fetching book for " + isbn); return "Book-" + isbn; } } // In main application or test: // bookService.findBook("123"); // bookService.findBook("123");
The @Cacheable annotation caches the result of the method for the given argument. On the first call, the method runs and prints the message. On the second call with the same argument, the cached result is returned without executing the method body, so no print occurs.
The correct annotation to enable caching in Spring Boot is @EnableCaching. It should be placed on a configuration or main application class, often alongside @SpringBootApplication.
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { @Cacheable("users") public String getUser(int id) { System.out.println("Loading user " + id); return "User-" + id; } } // Called from the same class method: // public void process() { // getUser(1); // getUser(1); // }
Spring caching uses proxies to intercept method calls. When a method annotated with @Cacheable is called from within the same class, the proxy is bypassed, so caching does not happen.
productService.getProduct(1); productService.getProduct(2); productService.getProduct(1); productService.getProduct(3); productService.getProduct(2);
The cache stores one entry per unique key. The calls with keys 1, 2, and 3 add three entries. Repeated calls with keys 1 and 2 do not add new entries.
@CacheEvict with allEntries=true clears all entries in the specified cache after the annotated method finishes successfully.