Spring boot ehcache 2 example

Learn to configure caching in spring boot application using ehcache 2.x. Learn to use annotation based cache config as well as manually updating cache with CacheManager.

1. Maven dependencies

In this example, we are using Spring boot version 1.5.13.RELEASE. Older spring boot versions support ehcache 2.x available under net.sf.ehcache package.

We need following dependencies to add caching capability.

  • spring-boot-starter-cache
  • ehcache (net.sf.ehcache)
  • cache-api (javax.cache)
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">



		<relativePath />



2. ehcache.xml

Spring boot automatically detects the presence of ehcache.xml in classpath and configure it. Here we provide the cache names, expiration time etc.

Find the complete list of attributes in the ehcache documentation.

	<diskStore path="java.io.tmpdir" />

	<defaultCache maxElementsInMemory="2000" 
			timeToLiveSeconds="1200" />
	<cache name="employeeCache" 
			timeToLiveSeconds="10000" />

3. @EnableCaching

It enables Spring’s annotation-driven cache management capability and enable support for interceptors when @Cacheable annotated methods are invoked.

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

public class CacheConfig {


4. @Cacheable Annotation

To cache data which is returned from a method call, we can use @Cacheable annotation on the method. Use it’s attributes cacheNames and key to refer to cache and key attribute of cache entry.

import java.util.HashMap;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

public class EmployeeManager 
	static HashMap<Long, Employee> db = new HashMap<>();
	static {
		db.put(1L, new Employee(1L, "Alex", "Gussin"));
		db.put(2L, new Employee(2L, "Brian", "Schultz"));
	@Cacheable(cacheNames="employeeCache", key="#id")
	public Employee getEmployeeById(Long id) {
		System.out.println("Getting employee from DB");
		return db.get(id);

5. CacheManager API

Sometimes we may want to use the caching in cases where using annotations might not seems perfect solution. In those cases, we can use org.springframework.cache.CacheManager and org.springframework.cache.Cache abstraction to access and utilize ehcache for adding and accessing cache entries.

To use CacheManager, we must first autowire into a spring component and the use it’s getCache(name) method to get the cache instance by it’s name.

Once we have access to the cache, we can use it’s get() and put() methods to add and access cache entries.


private CacheManager cacheManager;


Cache cache = cacheManager.getCache("myCache");
cache.put(3L, "Hello");
String value = cache.get(3L).get();

6. Spring boot ehcache 2 example – demo

I am creating a model class Employee whose instances will be cached.

import java.io.Serializable;

public class Employee implements Serializable 
	private static final long serialVersionUID = 5517244812959569947L;
	private Long id;
	private String firstName;
	private String lastName;

	public Employee() {

	public Employee(Long id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;

	//Getters and setters

	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";

Now in demo application class, I am testing the annotation based cache access using @Cacheable annotation and manual cache access using CacheManager.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

public class Application {

	private CacheManager cacheManager;
	private EmployeeManager employeeManager;

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

	public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
		return args -> {
			//This will hit the database 
			//This will hit the cache - verify the message in console output 
			//Access cache instance by name
			Cache cache = cacheManager.getCache("employeeCache");
			//Add entry to cache
			cache.put(3L, "Hello");
			//Get entry from cache

Program output.

Getting employee from DB
Employee [id=1, firstName=Alex, lastName=Gussin]

Employee [id=1, firstName=Alex, lastName=Gussin]		//Fetched from cache


Drop me your questions related to this spring boot cache example using ehcache in comments.

Happy Learning !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial