Hackforge Academy

Category: spring_boot

what is cache how to implement in spring boot

Published on 14 Jun 2026

Explanation

Slide 1: What is Cache? Cache is a temporary storage that keeps frequently accessed data in memory. Instead of fetching data from the database every time, the application can return data from the cache, improving performance and reducing database load.

Code:

// First Request -> Database -> Cache -> 
Response
// Next Requests -> Cache -> Response

Explanation

Slide 2: Enable Caching in Spring Boot Spring Boot provides caching support through the @EnableCaching annotation.

Code:

@SpringBootApplication
@EnableCaching
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(
DemoApplication.class, args);
    }
}

Explanation

Slide 3: Store Data in Cache using @Cacheable The first request fetches data from the database and stores it in the cache. Future requests return data directly from the cache.

Code:

@Service
public class UserService {

    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        System.out.println("Fetching from 
DB...");
        return userRepository.findById(id)
.orElse(null);
    }
}

Explanation

Slide 4: Update Cache using @CachePut When data is updated, @CachePut updates the cache with the latest value while also updating the database.

Code:

@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}

Explanation

Slide 5: Remove Cache using @CacheEvict When data is deleted or becomes invalid, @CacheEvict removes it from the cache. allEntries=true clears the entire cache.

Code:

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    userRepository.deleteById(id);
}

@CacheEvict(value = "users", allEntries =
 true)
public void clearCache() {
}

Explanation

Slide 6: Cache Providers Spring Boot supports multiple cache providers. ConcurrentMapCache is the default in-memory cache. Caffeine provides high-performance local caching. Redis is commonly used in production for distributed caching.

Code:

// Local Cache: ConcurrentMapCache, Caffeine
// Distributed Cache: Redis

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community