Bird
0
0

You want to cache results of a method that returns a list of users filtered by role. How do you ensure caching works correctly for different roles?

hard📝 component behavior Q8 of 15
Spring Boot - Caching
You want to cache results of a method that returns a list of users filtered by role. How do you ensure caching works correctly for different roles?
AUse <code>@Cacheable(cacheNames = "users")</code> without key; caching will auto-differentiate.
BUse <code>@Cacheable(cacheNames = "users", key = "#role")</code> to cache by role parameter.
CUse <code>@Cacheable(cacheNames = "users", key = "#root.methodName")</code> to cache by method name.
DCaching cannot be used with methods returning lists.
Step-by-Step Solution
Solution:
  1. Step 1: Understand caching by method parameters

    To cache results differently based on the role parameter, specify a key using SpEL expression referencing the role.

  2. Step 2: Evaluate options

    Use @Cacheable(cacheNames = "users", key = "#role") to cache by role parameter. correctly uses key = "#role" to cache by role. Use @Cacheable(cacheNames = "users") without key; caching will auto-differentiate. caches all calls under same key, causing wrong reuse. Use @Cacheable(cacheNames = "users", key = "#root.methodName") to cache by method name. caches by method name only, ignoring parameters. Caching cannot be used with methods returning lists. is false.

  3. Final Answer:

    Use @Cacheable(cacheNames = "users", key = "#role") to cache by role parameter. -> Option B
  4. Quick Check:

    Use key to cache by parameter [OK]
Quick Trick: Use key attribute to cache by specific parameter [OK]
Common Mistakes:
  • Not specifying key for parameter-based caching
  • Caching by method name only
  • Thinking lists can't be cached

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes