Bird
Raised Fist0
Spring Bootframework~10 mins

@Cacheable for read caching in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @Cacheable for read caching
Method call with key
↓
Check cache for key
↓
Return cached
↓
Return value
↓
Return value
When a method annotated with @Cacheable is called, Spring checks if the result is in cache. If yes, it returns cached data. If no, it runs the method, caches the result, then returns it.
Execution Sample
Spring Boot
@Cacheable("books")
public Book findBookById(Long id) {
  // simulate slow DB call
  return bookRepository.findById(id).orElse(null);
}
This method caches the book found by id. On first call, it fetches from DB and caches. Next calls with same id return cached book.
Execution Table
StepMethod CallCache CheckCache Hit?ActionReturned Value
1findBookById(1)Check cache for key=1NoCall method, fetch from DBBook{id=1, title='Java Basics'}
2Store result in cache with key=1--Cache updated-
3findBookById(1)Check cache for key=1YesReturn cached valueBook{id=1, title='Java Basics'}
4findBookById(2)Check cache for key=2NoCall method, fetch from DBBook{id=2, title='Spring Guide'}
5Store result in cache with key=2--Cache updated-
6findBookById(2)Check cache for key=2YesReturn cached valueBook{id=2, title='Spring Guide'}
💡 Method calls end when all requested keys are served either from cache or DB.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4After Step 5Final
cacheemptyempty{1: Book{id=1}}{1: Book{id=1}}{1: Book{id=1}, 2: Book{id=2}}{1: Book{id=1}, 2: Book{id=2}}
Key Moments - 2 Insights
Why does the method not run on the second call with the same id?
Because the cache already has the result for that id (see execution_table step 3), so Spring returns cached data without running the method.
What happens if the cache does not have the key?
The method runs normally to get fresh data, then the result is stored in cache (see steps 1 and 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is returned at step 3?
ACached Book{id=1, title='Java Basics'}
BNew DB call result
CNull
DError
💡 Hint
Check the 'Returned Value' column at step 3 in execution_table.
At which step does the cache first get updated with key=2?
AStep 6
BStep 4
CStep 5
DStep 3
💡 Hint
Look for 'Store result in cache with key=2' in execution_table.
If the cache was empty initially, what would happen at step 1?
ACache returns stale data
BMethod runs and caches result
CMethod returns null
DMethod throws exception
💡 Hint
See execution_table step 1 and 2 for cache miss behavior.
Concept Snapshot
@Cacheable annotation caches method results by key.
On method call, cache is checked first.
If hit, cached value is returned immediately.
If miss, method runs and result is cached.
Improves performance by avoiding repeated DB calls.
Full Transcript
The @Cacheable annotation in Spring Boot helps store method results in a cache. When a method with @Cacheable is called, Spring checks if the result for the given key is already cached. If yes, it returns the cached result without running the method again. If no, it runs the method, stores the result in the cache, and then returns it. This saves time by avoiding repeated slow operations like database calls. For example, calling findBookById(1) first time fetches from DB and caches the book. The next call with id 1 returns the cached book instantly. The execution table shows each step: checking cache, method execution, caching, and returning values. The variable tracker shows how the cache grows as new keys are added. This caching pattern is useful for read-heavy methods where data changes infrequently.

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

  1. 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.
  2. Step 2: Identify the main benefit

    This caching avoids repeated slow or expensive operations, improving performance.
  3. Final Answer:

    To store the result of a method call and reuse it for the same inputs to improve performance. -> Option A
  4. 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

  1. Step 1: Recall the correct attribute name for cache name

    The correct attribute to specify cache names in @Cacheable is cacheNames.
  2. 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.
  3. Final Answer:

    @Cacheable(cacheNames = "users") public User getUserById(Long id) { ... } -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Fetching data for 5 -> Option D
  4. 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:
@Cacheable(cacheNames = "items")
public Item getItem(Long id) {
    return itemRepository.findById(id).get();
}

// Usage
getItem(null);
medium
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

  1. 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.
  2. 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.
  3. Final Answer:

    Missing @EnableCaching annotation causes caching to fail silently. -> Option C
  4. 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

  1. Step 1: Understand conditional caching with condition

    The condition attribute controls when caching happens. It caches only if the condition is true.
  2. 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.
  3. Final Answer:

    @Cacheable(cacheNames = "products", condition = "#category != null && #category != ''") public Product findProduct(String category, int id) { ... } -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard