Q1. How does caching work in Spring?
Spring provides a caching abstraction that allows you to add caching to methods without coupling to a specific cache implementation.
Use annotations like
Enable caching with
The actual cache store (e.g., ConcurrentHashMap, Ehcache, Redis) is pluggable.
Use annotations like
@Cacheable, @CacheEvict, @CachePut.Enable caching with
@EnableCaching.The actual cache store (e.g., ConcurrentHashMap, Ehcache, Redis) is pluggable.
Q2. What is @Cacheable?
When the method is called, Spring checks if the result is already in the cache; if so, it returns the cached value without executing the method.
Parameters:
@Cacheable indicates that the result of a method should be cached.When the method is called, Spring checks if the result is already in the cache; if so, it returns the cached value without executing the method.
Parameters:
value (cache name), key (SpEL expression), condition, unless.Q3. What is @CacheEvict?
It can be triggered before or after method execution (by default after).
Use
@CacheEvict is used to remove entries from the cache.It can be triggered before or after method execution (by default after).
Use
allEntries=true to clear the entire cache.Q4. What is @CachePut?
It does not skip execution like
Useful for cache updates after a create/update operation.
@CachePut always executes the method and updates the cache with the result.It does not skip execution like
@Cacheable.Useful for cache updates after a create/update operation.
Q5. How do you use Redis as a cache provider?
Add
Spring Boot auto-configures
Configure Redis connection properties.
Then use caching annotations as usual.
spring-boot-starter-data-redis dependency.Spring Boot auto-configures
RedisCacheManager.Configure Redis connection properties.
Then use caching annotations as usual.
