Bird
0
0

Identify the error in the following code using @Cacheable:

medium📝 Debug Q14 of 15
Spring Boot - Caching
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);
ACalling getItem with null causes NullPointerException because cache key is null.
BCache name "items" is invalid and causes syntax error.
CMissing @EnableCaching annotation causes caching to fail silently.
DMethod must be static to use @Cacheable.
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes