How to work with Spring Cache | Spring Boot

Performance is a big problem in software development. And Caching is one solution to speed up system. The tutorial will guide you how to start with Spring Cache using Spring Boot.

Related posts:
Couchbase – How to create Spring Cache Couchbase application with SpringBoot
SpringBoot Caffeine cache with PostgreSQL backend

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE

II. Overview
1. Goal

Our goal is to build a service that can receive RESTful request from Client, cache or evict Customer Data by it own Component called CacheService, and return the result.
Note that spring provides only the caching abstraction, but the actual caching store is not implemented by spring caching framework. But Spring Boot has auto-configuration of caching technologies, we don’t have to create our caching storage, and we just cache Customer Data with target name ‘customers’.

2. Project Structure

Customer will be Plain Old Java Object
CacheService is the Component we use to cache data and store in a target cache named “customers” and it will be autowired in WebController to implement caching method.
WebController is a RestController which has request mapping method for Restful Request such as cacheput, cachable, cacheevict.
SpringBootApplication should be enable caching.
Dependencies for Spring Boot Starter are added in pom.xml.

3. Step to do

– Create Spring Boot project & add Dependencies
– Create a DataModel class
– Create a Caching Service
– Create a Web Controller
– Enable Caching
– Run Spring Boot Application & Enjoy Result

4. Demo Video

III. Practice
1. Create Spring Boot project & add Dependencies

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:
Click Next, then click Finish. Spring Boot project will be created successfully.

Now, add dependencies for Web MVC, and Spring Caching
Open pom.xml, add:

2. Create a DataModel class

Under package model, create class Customer.

Content of

3. Create a Caching Service

Create a Caching Service class under package service. This is the most important part of the tutorial.

Content of

We have some necessary cache annotations that attached to each method:

@Cacheable is one of the most important and common annotation for caching the requests.
If the application sends multiple requests, this annotation will not execute the method which is Cachable multiple times, instead it will return the result from the cached storage.
+ value is a cache name to store the caches, in this case, it’s customers.
+ key is a Spring Expression Language for computing the key dynamically.
+ input parameter ID is used as a key to find Customer object in the cache if it exists, if the customer with that id doesn’t exist, Spring Framework will execute command inside method (including Sleep function – for simulation purpose) and cache current customer object that is returned in this method.

@CachePut updates the cache which is stored and execute the method.
+ the method putCustomer is used to modify customer instance in the cache.
+ input parameter ID is used as a key to find customer object in the cache. If the id exists, the function will modify the firstName the same as the input string parameter.

@CacheEvict is used for removing a single cache or clearing the entire cache from the cache storage. The method evict uses the input parameter id as a key to find the object that has the same id and removes it from the cache.

4. Create a Web Controller

WebController is a RestController, we autowire service for CacheService that we created at previous step.
We have some methods that have request mapping: get, put, evict.

Content of

– @RequestMapping(“/cacheput”): put a Customer to cache data to target customers by service.
– @RequestMapping(“/cachable”): get a Customer from cache customers by service.
– @RequestMapping(“/cacheevict”): delete a Customer with input ID from cache customers by service.

5. Enable Caching

By default, Caching in spring is not enabled. We must enable the caching by annotating with @EnableCaching or declaring it in the XML file.
In our tutorial, we enable caching by add annotation @EnableCaching for the SpringBootApplication class.

6. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
Service process slowly and result:

Server has displayed a text on console:

Now a customer with Customer(1, “Jack”, “Smith”) has been cached.

Request 2
Now the response is faster because Customer with id = 1 has been cached before, the application just get data from cache storage.


Request 3
Message is returned on Browser:
Now customer with id=1 is modified: firstname=”Peter”, not “Jack”.

Request 4
Response is faster BUT the result is difference from first request:

cacheable request 4

Request 5
Make a cache-evict request:
Browser displays:
Now customer with id=1 was evicted from cache storage.

Request 6
Now the behavior of the browser is the same as the first request because customer with id=1 was evicted to cache, and the method under @Cachable is executed.
Service process slowly and result:

cacheable request 4

Server, of course, displays a text on console:

IV. Source Code


Related Posts

1 thought on “How to work with Spring Cache | Spring Boot”

Got Something To Say:

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