Spring Boot Caching

Srini
2 min readNov 16, 2020

--

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 @EnableCachingannotation 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 @CacheEvictannotations. 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:

--

--

No responses yet