Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

How do we configure caching in SpringBoot applications? What are the annotations used for caching? 

How to Configure Caching in Spring Boot Applications


1: Enable Caching:

Add @EnableCaching annotation in your main application class.


2: Add Cache Dependency:

Include a cache provider in your pom.xml (like EhCache, Redis, or use default).


3: Use Caching Annotations in Your Code:

A: @Cacheable: Marks a method whose result should be cached.

B: @CachePut: Updates the cache with the new value.

C: @CacheEvict: Removes data from the cache.


@EnableCaching
@SpringBootApplication
public class MyApp { ... }

@Cacheable("users")
public User getUserById(Long id) { ... }

@CachePut("users")
public User updateUser(User user) { ... }

@CacheEvict("users")
public void deleteUser(Long id) { ... }


Summary:

1: Use @EnableCaching to turn on caching.

2: Use @Cacheable, @CachePut, and @CacheEvict to manage cache in methods.

Ready for commit