0
0
Spring Bootframework~30 mins

@CacheEvict for invalidation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @CacheEvict for Cache Invalidation in Spring Boot
📖 Scenario: You are building a simple Spring Boot service that manages user profiles. To improve performance, you cache user data. When a user profile is updated, you need to clear the cached data to keep it fresh.
🎯 Goal: Build a Spring Boot service with a method to cache user profiles and another method to update profiles that uses @CacheEvict to clear the cache for the updated user.
📋 What You'll Learn
Create a simple UserService class with a method getUserById that returns a user name string.
Add a cache configuration to cache the result of getUserById.
Create an updateUserName method that updates the user name and uses @CacheEvict to clear the cache for that user ID.
Ensure the cache is cleared only for the specific user ID when updateUserName is called.
💡 Why This Matters
🌍 Real World
Caching user data improves performance by avoiding repeated database calls. Clearing cache on updates ensures users see fresh data.
💼 Career
Understanding cache invalidation with <code>@CacheEvict</code> is essential for backend developers working with Spring Boot to build efficient and consistent applications.
Progress0 / 4 steps
1
Create UserService with getUserById method
Create a class called UserService with a method getUserById that takes a Long userId parameter and returns a String user name. For now, return the string "User" + userId.
Spring Boot
Need a hint?

Define a public class UserService. Inside it, create a public method getUserById that returns a string combining "User" and the userId.

2
Enable caching and add @Cacheable to getUserById
Add the @Cacheable annotation to the getUserById method with cache name "users". Also, add the @Service annotation to the UserService class to make it a Spring service.
Spring Boot
Need a hint?

Use @Service on the class and @Cacheable("users") on the getUserById method to enable caching.

3
Add updateUserName method with @CacheEvict
Add a method updateUserName that takes Long userId and String newName parameters. Annotate it with @CacheEvict(cacheNames = "users", key = "#userId") to clear the cache for that user ID. Inside the method, simulate updating by returning newName.
Spring Boot
Need a hint?

Create updateUserName method annotated with @CacheEvict to clear cache for the given userId.

4
Add @EnableCaching to application configuration
Create a configuration class called CacheConfig annotated with @Configuration and @EnableCaching to enable Spring caching support.
Spring Boot
Need a hint?

Create a class CacheConfig with @Configuration and @EnableCaching annotations to activate caching.