Bird
0
0

Given the following method annotated with @Cacheable("books"), what happens when getBook(5) is called twice?

medium📝 component behavior Q4 of 15
Spring Boot - Caching
Given the following method annotated with @Cacheable("books"), what happens when getBook(5) is called twice?
@Cacheable("books")
public Book getBook(int id) {
  System.out.println("Fetching book " + id);
  return bookRepository.findById(id);
}
AThe message prints twice; cache is not used
BThe message prints once; second call throws exception
CThe message never prints; cache is preloaded
DThe message prints once; second call returns cached Book without printing
Step-by-Step Solution
Solution:
  1. Step 1: Understand @Cacheable behavior

    On first call, method executes and caches result; on second call with same argument, cached result returns without method execution.
  2. Step 2: Analyze output

    Message prints only on first call; second call returns cached Book silently.
  3. Final Answer:

    The message prints once; second call returns cached Book without printing -> Option D
  4. Quick Check:

    @Cacheable caches method call result [OK]
Quick Trick: First call runs method; later calls use cache [OK]
Common Mistakes:
  • Assuming method runs every time despite caching
  • Thinking cache preloads data automatically
  • Believing second call throws error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes