📖 Scenario: You are building a simple Spring Boot application that fetches user details from a database. To improve performance, you want to cache the user data when it is read, so repeated requests for the same user do not hit the database every time.
🎯 Goal: Learn how to use the @Cacheable annotation in Spring Boot to cache method results for faster read access.
📋 What You'll Learn
Create a service class with a method to get user details by ID
Add a cache configuration variable
Use @Cacheable annotation on the method to enable caching
Complete the Spring Boot application setup to support caching
💡 Why This Matters
🌍 Real World
Caching read data like user details reduces database load and speeds up response times in web applications.
💼 Career
Understanding and implementing caching with Spring Boot is a common requirement for backend developers to optimize application performance.
Progress0 / 4 steps
1
Create UserService with getUserById method
Create a class called UserService with a method getUserById that takes a Long id parameter and returns a String representing user details. Inside the method, return the string "User details for id: " + id.
Spring Boot
Hint
Define a public class named UserService. Inside it, create a public method getUserById that returns a string combining the fixed text and the id parameter.
2
Add cache name configuration
Inside the UserService class, add a public static final String variable called CACHE_NAME and set it to "users".
Spring Boot
Hint
Define a constant string CACHE_NAME inside the class to hold the cache name "users".
3
Add @Cacheable annotation to getUserById method
Import org.springframework.cache.annotation.Cacheable and annotate the getUserById method with @Cacheable(cacheNames = UserService.CACHE_NAME) to enable caching of the method's return value.
Spring Boot
Hint
Use the @Cacheable annotation above the method and specify the cache name using the constant UserService.CACHE_NAME.
4
Enable caching in Spring Boot application
In your main Spring Boot application class, import org.springframework.cache.annotation.EnableCaching and add the @EnableCaching annotation above the class declaration to activate caching support.
Spring Boot
Hint
Import @EnableCaching and place it above the main application class to enable caching features in Spring Boot.
Practice
(1/5)
1. What is the main purpose of using @Cacheable in a Spring Boot application?
easy
A. To store the result of a method call and reuse it for the same inputs to improve performance.
B. To delete data from the database automatically.
C. To make a method run asynchronously in a separate thread.
D. To validate user input before processing.
Solution
Step 1: Understand what @Cacheable does
@Cacheable stores 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 A
Quick Check:
@Cacheable purpose = store and reuse results [OK]
Hint: Remember: @Cacheable speeds up repeated reads by caching results [OK]
Common Mistakes:
Thinking @Cacheable deletes or modifies data
Confusing caching with asynchronous execution
Assuming it validates inputs automatically
2. Which of the following is the correct way to use @Cacheable on a method named getUserById with cache name "users"?
easy
A. @Cacheable(cacheNames = "users") public User getUserById(Long id) { ... }
B. @Cacheable(name = "users") public User getUserById(Long id) { ... }
C. @Cacheable(cache = "users") public User getUserById(Long id) { ... }
D. @Cacheable(cacheName = "users") public User getUserById(Long id) { ... }
Solution
Step 1: Recall the correct attribute name for cache name
The correct attribute to specify cache names in @Cacheable is cacheNames.
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 A
Quick Check:
Correct attribute = cacheNames [OK]
Hint: Use cacheNames, not name or cache, in @Cacheable [OK]
Common Mistakes:
Using wrong attribute like name or cache instead of cacheNames
Missing parentheses or quotes around cache name
Placing @Cacheable on class instead of method
3. Given the following code snippet, what will be printed when getData(5) is called twice?
@Cacheable(cacheNames = "dataCache")
public int getData(int id) {
System.out.println("Fetching data for " + id);
return id * 2;
}
medium
A. Fetching data for 5
Fetching data for 10
B. Fetching data for 5
Fetching data for 5
C. No output printed
D. Fetching data for 5
Solution
Step 1: Understand caching effect on method calls
The first call to getData(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 D
Quick Check:
Cached call skips print = only one print [OK]
Hint: Cached calls skip method body, so no repeated prints [OK]
Common Mistakes:
Assuming method runs every time and prints twice
Thinking cache stores only values, not skips method
Confusing argument values causing cache miss
4. Identify the error in the following code using @Cacheable:
A. Calling getItem with null causes NullPointerException because cache key is null.
B. Cache name "items" is invalid and causes syntax error.
C. Missing @EnableCaching annotation causes caching to fail silently.
D. Method must be static to use @Cacheable.
Solution
Step 1: Check required configuration for caching
@EnableCaching must be present on a @Configuration class to activate Spring's caching support. Without it, @Cacheable has no effect and caching fails silently.
Step 2: Rule out distractors
Cache name "items" is valid. Null arguments are handled via NullValue.INSTANCE in 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 C
Quick Check:
@EnableCaching required for caching [OK]
Hint: Always add @EnableCaching to a @Configuration class [OK]
Common Mistakes:
Assuming cache name "items" is invalid
Thinking null causes NullPointerException due to cache key
Believing method must be static for @Cacheable
5. You want to cache results of a method findProduct(String category, int id) but only cache when category is not null or empty. Which @Cacheable usage correctly implements this conditional caching?
hard
A. @Cacheable(cacheNames = "products", unless = "#category == null || #category == ''")
public Product findProduct(String category, int id) { ... }
B. @Cacheable(cacheNames = "products", condition = "#category != null && #category != ''")
public Product findProduct(String category, int id) { ... }
C. @Cacheable(cacheNames = "products", key = "#category + #id")
public Product findProduct(String category, int id) { ... }
D. @Cacheable(cacheNames = "products", condition = "#id > 0")
public Product findProduct(String category, int id) { ... }
Solution
Step 1: Understand conditional caching with condition
The condition attribute 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 if category is not null and not empty, matching the requirement. @Cacheable(cacheNames = "products", unless = "#category == null || #category == ''")
public Product findProduct(String category, int id) { ... } uses unless which 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 on id, not category.
Final Answer:
@Cacheable(cacheNames = "products", condition = "#category != null && #category != ''")
public Product findProduct(String category, int id) { ... } -> Option B
Quick Check:
Use condition to cache only when category valid [OK]
Hint: Use condition attribute to control caching logic [OK]
Common Mistakes:
Confusing condition and unless attributes
Not checking for empty string in condition
Using key attribute instead of condition for caching control
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.