This post will discuss how to enable caching in Spring Boot.

Caching is a technique that improves the performance and scalability of a web application by storing frequently used data or results in memory or other storage systems. Caching can reduce the number of database queries, network calls, or computations that are needed to serve a request. Spring Boot provides a powerful and easy-to-use caching abstraction that supports various caching implementations and annotations.

 
There are several ways to enable caching in Spring Boot, depending on the desired caching provider and configuration. Here are some of the possible methods:

1. Using @EnableCaching Annotation

This is the simplest and most common way to enable caching in Spring Boot. The @EnableCaching annotation activates the Spring caching support and scans the application for any methods that are annotated with @Cacheable, @CachePut, @CacheEvict, or @Caching. These annotations allow us to specify which methods should be cached, how to update or invalidate the cache, and other cache-related settings. The following code illustrates this:

2. Using spring.cache.type Property

This is a way to configure the type of cache provider that Spring Boot should use. By default, Spring Boot will use a simple in-memory cache based on a ConcurrentMap. However, we can change this behavior by setting the spring.cache.type property in the application.properties file or as an environment variable. The possible values for this property are: none, simple, caffeine, ehcache, hazelcast, infinispan, jcache, couchbase, redis, or generic. For instance:

# Use Redis as the cache provider
spring.cache.type=redis
 
# Configure the Redis connection properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=secret

3. Using Custom CacheManager Bean

This is a way to customize the cache provider and configuration programmatically. We can create a bean of type CacheManager in our configuration class and configure it with various properties and options. For example, we can use Caffeine as our cache provider and set the maximum size and expiration time for each cache. The following code illustrates this:

That’s all about ways to enable caching in Spring Boot.