@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.
Practice
@Cacheable in a Spring Boot application?Solution
Step 1: Understand what
@Cacheabledoes@Cacheablestores the output of a method so that if the method is called again with the same inputs, it returns the stored result instead of running the method again.Step 2: Identify the main benefit
This caching avoids repeated slow or expensive operations, improving performance.Final Answer:
To store the result of a method call and reuse it for the same inputs to improve performance. -> Option AQuick Check:
@Cacheable purpose = store and reuse results [OK]
- Thinking @Cacheable deletes or modifies data
- Confusing caching with asynchronous execution
- Assuming it validates inputs automatically
@Cacheable on a method named getUserById with cache name "users"?Solution
Step 1: Recall the correct attribute name for cache name
The correct attribute to specify cache names in@CacheableiscacheNames.Step 2: Match the syntax with the method
@Cacheable(cacheNames = "users") public User getUserById(Long id) { ... } uses@Cacheable(cacheNames = "users")which is correct syntax for Spring Boot caching.Final Answer:
@Cacheable(cacheNames = "users") public User getUserById(Long id) { ... } -> Option AQuick Check:
Correct attribute = cacheNames [OK]
- Using wrong attribute like name or cache instead of cacheNames
- Missing parentheses or quotes around cache name
- Placing @Cacheable on class instead of method
getData(5) is called twice?@Cacheable(cacheNames = "dataCache")
public int getData(int id) {
System.out.println("Fetching data for " + id);
return id * 2;
}Solution
Step 1: Understand caching effect on method calls
The first call togetData(5)runs the method and prints "Fetching data for 5". The result (10) is cached.Step 2: Analyze the second call with same argument
The second call with argument 5 returns cached result without running the method body, so no print happens.Final Answer:
Fetching data for 5 -> Option DQuick Check:
Cached call skips print = only one print [OK]
- Assuming method runs every time and prints twice
- Thinking cache stores only values, not skips method
- Confusing argument values causing cache miss
@Cacheable:@Cacheable(cacheNames = "items")
public Item getItem(Long id) {
return itemRepository.findById(id).get();
}
// Usage
getItem(null);Solution
Step 1: Check required configuration for caching
@EnableCachingmust be present on a@Configurationclass to activate Spring's caching support. Without it,@Cacheablehas no effect and caching fails silently.Step 2: Rule out distractors
Cache name "items" is valid. Null arguments are handled viaNullValue.INSTANCEin the default key generator, no exception from cache key. Methods do not need to be static.Final Answer:
Missing @EnableCaching annotation causes caching to fail silently. -> Option CQuick Check:
@EnableCaching required for caching [OK]
- Assuming cache name "items" is invalid
- Thinking null causes NullPointerException due to cache key
- Believing method must be static for @Cacheable
findProduct(String category, int id) but only cache when category is not null or empty. Which @Cacheable usage correctly implements this conditional caching?Solution
Step 1: Understand conditional caching with
Theconditionconditionattribute controls when caching happens. It caches only if the condition is true.Step 2: Analyze each option
@Cacheable(cacheNames = "products", condition = "#category != null && #category != ''") public Product findProduct(String category, int id) { ... } caches only ifcategoryis not null and not empty, matching the requirement. @Cacheable(cacheNames = "products", unless = "#category == null || #category == ''") public Product findProduct(String category, int id) { ... } usesunlesswhich caches unless the condition is true, so it inverts logic. @Cacheable(cacheNames = "products", key = "#category + #id") public Product findProduct(String category, int id) { ... } only sets key, no condition. @Cacheable(cacheNames = "products", condition = "#id > 0") public Product findProduct(String category, int id) { ... } caches based onid, notcategory.Final Answer:
@Cacheable(cacheNames = "products", condition = "#category != null && #category != ''") public Product findProduct(String category, int id) { ... } -> Option BQuick Check:
Use condition to cache only when category valid [OK]
- Confusing condition and unless attributes
- Not checking for empty string in condition
- Using key attribute instead of condition for caching control
Ready to prove it?
Pass the test and this pattern moves unknown
