Spring boot 2 and ehcache 3 example

Learn to configure caching in spring boot application using ehcache 3.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 2.1.6.RELEASE. Older spring boot versions support ehcache 2.x available under net.sf.ehcache package. New versions of Spring boot support ehcache 3.x available under org.ehcache package.

Ehcache version 3 is an implementation of a JSR-107 cache manager.

We need following dependencies to add caching capability.

  • spring-boot-starter-cache
  • ehcache (org.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. application.properties

Spring’s auto-configuration finds Ehcache’s implementation of JSR-107. However, no caches are created by default because neither Spring nor Ehcache looks for a default ehcache.xml file. We must specifically provide the ehcache configuration file path which has to be used.


3. ehcache.xml

In ehcache.xml file, configure the cache names and their attributes.

Find the complete list of attributes in the ehcache documentation.


        <jsr107:defaults enable-statistics="true"/>

    <cache alias="employeeCache">
            <ttl unit="seconds">10000</ttl>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">100</offheap>

4. CacheEventListener

We have also used the event listener which shall be logging the cache events when cache entries are created, removed or updated.

package com.company;

import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomCacheEventLogger implements CacheEventListener<Object, Object> {

	private static final Logger LOG = LoggerFactory.getLogger(CustomCacheEventLogger.class);

	public void onEvent(CacheEvent cacheEvent) {
		LOG.info("Cache event = {}, Key = {},  Old value = {}, New value = {}", cacheEvent.getType(),
				cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue());

5. @EnableCaching

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

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

public class CacheConfig {


6. @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);

7. Spring 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();

8. Spring boot ehcache 3 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, new Employee(3L, "Charles", "Dave"));
			//Get entry from cache

Program output.

//First hit to "employeeManager.getEmployeeById(1L)"

Getting employee from DB
Employee [id=1, firstName=Alex, lastName=Gussin]
2019-07-10 15:42:32.371  INFO 11956 --- [e [_default_]-0] com.company.CustomCacheEventLogger       
: Cache event = CREATED, Key = 1,  Old value = null, New value = Employee [id=1, firstName=Alex, lastName=Gussin]

//Second hit to "employeeManager.getEmployeeById(1L)"
Employee [id=1, firstName=Alex, lastName=Gussin]

//cache.put(3L, new Employee(3L, "Charles", "Dave"));
2019-07-10 15:42:32.399  INFO 11956 --- [e [_default_]-0] com.company.CustomCacheEventLogger       : Cache event = CREATED, Key = 3,  Old value = null, New value = Employee [id=3, firstName=Charles, lastName=Dave]

Employee [id=3, firstName=Charles, lastName=Dave]

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

Happy Learning !!

Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

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.