Home » EnableCaching Spring Boot

EnableCaching Spring Boot

  • by
EnableCaching Spring Boot

1. Overview

In this article, we will discuss the purpose of annotation EnableCaching in the Spring boot application.

A cache is always hidden and neither producer nor consumer is aware that caching occurs. It as well improves performance but does that by allowing the same data to be read multiple times in a fast fashion.

To learn more about Spring caching, refer to these articles.

2. Spring cache abstraction

Spring Framework provides support for transparently adding caching into an existing Spring application.

At its core, the Spring applies the caching to Java methods, reducing thus the number of executions based on the information available in the cache. Whenever the application executes a targeted method, the cache abstraction will apply a caching behavior checking whether the application has already executed the method with the provided arguments.

If the cached result is already available, then returns the result without having to execute the actual method. If it has not, then executes the method, stores the result in the cache. Finally, returns the result to the user. Then next time returns the cached result whenever the method is invoked.

This way, Spring executes the expensive invocations (whether CPU or IO bound) only once for the provided parameters. Then re-uses the result without having to actually execute the method again. Spring applies the caching logic transparently without any interference to the invoker.

3. EnableCaching in Spring boot app

You can use @EnableCaching annotation with @Configuration classes.

The @EnableCaching annotation triggers a post-processor that inspects every Spring bean for caching annotations on public methods. If Spring finds any such cache annotation, it automatically creates a proxy to intercept the method call and handle the caching behavior accordingly.

The post-processor handles the @Cacheable@CachePut and @CacheEvict annotations.

Spring Boot automatically configures a suitable CacheManager to serve as a provider for the relevant cache.

By default, Spring uses the ConcurrentHashMap as a cache store but supports a wide variety of caching libraries and fully complies with JSR-107 (JCache).

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

public class CachingApplication {

  public static void main(String[] args) {
    SpringApplication.run(CachingApplication.class, args);


4. Conclusion

To sum up, we have learned basis of EnableCaching in Spring boot application. You can find more code samples in our GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *