We use caches to avoid database invocation or cost-intensive calculations. Spring provides an Abstraction layer for implementing the Cache.
Why do we need an abstraction layer?
There are various Cache providers with their own API spec. If we want to use one of them for our application, we need to have a hard dependency on these Cache provider’s API. The Spring Cache Abstraction layer gives use the ability to use the caching mechanism provided by various providers without calling cache provider’s API directly.
How it is done?
- Spring Boot users can use the spring-boot-starter-cache starter package to easily add the caching:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- The
@EnableCaching
annotation triggers a post-processor that inspects every Spring bean for the presence of caching annotations on public methods. If such an annotation is found, a proxy is automatically created to intercept the method call and handle the caching behavior accordingly. - The post-processor handles the
@Cacheable
and@CacheEvict
annotations. You can refer to the Javadoc and the reference guide for more detail. - Spring Boot automatically configures a suitable
CacheManager
to serve as a provider for the relevant cache. See the Spring Boot documentation for more detail. - If we don’t specify a specific caching library, then the default cache store is the simple fallback that uses ConcurrentHashMap.
- The caching abstraction supports a wide range of cache libraries and is fully compliant with JSR-107 (JCache).
- If the CacheManager is auto-configured by Spring Boot, you can further tune its configuration before it is fully initialized by exposing a bean that implements the CacheManagerCustomizer interface.
References:
- Caching Data with Spring: This guide walks us through the process of enabling caching on a Spring managed bean.
- 33. Caching
- The complete guide for Spring Cache Abstraction
- Guide to Spring caching
- https://www.youtube.com/watch?v=SpQzWtqulhM&ab_channel=SpringI%2FO
- A Guide To Caching in Spring | Baeldung