Sitemap
Javarevisited

A humble place to learn Java and Programming better.

Spring Boot @Cacheable Annotation – Improve Performance with Caching

4 min readMar 9, 2025

--

🚀 Introduction: Why Use @Cacheable in Spring Boot?

1️⃣ Enabling Caching in Spring Boot

@Configuration
@EnableCaching
public class CacheConfig {
}

2️⃣ Using @Cacheable to Cache Method Results

✅ Example: Basic @Cacheable Usage

@Service
public class UserService {

@Cacheable("users")
public User getUserById(Long id) {
System.out.println("Fetching user from database...");
return new User(id, "John Doe");
}
}

3️⃣ Configuring a Cache Provider in Spring Boot

3.1 Using the Default In-Memory Cache (No Configuration Required)

3.2 Using Redis as a Cache Provider

✅ Step 1: Add Redis Dependencies in pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

✅ Step 2: Configure Redis in application.properties

spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379

✅ Step 3: Define a RedisCacheManager

@Configuration
@EnableCaching
public class RedisConfig {

@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // Set TTL for cache entries
.disableCachingNullValues();
}
}

4️⃣ @Cacheable Key and Condition Parameters

4.1 Using key to Customize Cache Keys

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) { ... }

4.2 Using condition to Control Caching

@Cacheable(value = "users", condition = "#id > 10")
public User getUserById(Long id) { ... }

5️⃣ Removing Cached Data with @CacheEvict

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
System.out.println("User deleted from database.");
}

5.1 Clearing the Entire Cache

@CacheEvict(value = "users", allEntries = true)
public void deleteAllUsers() {
System.out.println("All users deleted from cache.");
}

6️⃣ Updating Cache Entries with @CachePut

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
System.out.println("Updating user in database...");
return user;
}

7️⃣ Combining @Cacheable, @CacheEvict, and @CachePut

✅ Example: Complete Caching Service

@Service
public class UserService {

@Cacheable("users")
public User getUserById(Long id) {
System.out.println("Fetching user from database...");
return new User(id, "John Doe");
}

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
System.out.println("User deleted from database.");
}

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
System.out.println("Updating user in database...");
return user;
}
}

🎯 Conclusion: Why Use @Cacheable in Spring Boot?

--

--

Responses (1)