Spring Boot and Ehcache 3 Example

Learn to configure caching in Spring boot application using Ehcache 3.x (JSR-107). Learn to use annotation-based cache config and caching annotations as well as manually update the cache with CacheManager.

1. Maven

1.1. With Spring Boot 3

In Spring Boot 3, we can add the Ehcahce 3.10.x support with the following dependencies. It supports the Jakarta namespace that is needed since Spring Boot 3.


1.2. With Spring Boot 2

To add ehcache in Spring Boot 2 applications with legacy JAXB namespaces, we can add the following dependencies:


2. Spring Caching with Ehcache

2.1. @EnableCaching

The @EnableCaching annotation enables Spring’s annotation-driven cache management capability and enables 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 {


2.2. Cache Configuration

Springs auto-configuration with spring-boot-starter-cache finds Ehcache in the classpath and configures it automatically, once we have added the ehcache.xml file in the classpath.


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>
      <offheap unit="MB">100</offheap>

3. CacheEventListener

It is a good idea to log the cache events in the log file for debugging purposes in case we have issues in production. We can use the following event listener which shall be logging the cache events when cache entries are created, removed or updated.

import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

4. Using @Cacheable Annotation

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

public class EmployeeService {
  @Cacheable(cacheNames="employeeCache", key="#id")
  public Employee getEmployeeById(Long id) {
    log.info("Getting employee from DB");
    return repository.get(id);

5. Spring CacheManager API

Sometimes we may want to use caching in cases where using annotations might not seem the 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 use its getCache(name) method to get the cache instance by its 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("employeeCache");
cache.put(3L, "Hello");
String value = cache.get(3L).get();

6. Demo

We are creating a model class Employee whose instances will be cached.

public class Employee implements Serializable {

  private Long id;
  private String firstName;
  private String lastName;

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

public class App implements CommandLineRunner {

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

  private CacheManager cacheManager;

  private EmployeeService employeeService;

  public void run(String... args) throws Exception {

    //This will hit the database

    //This will hit the cache - verify the message in console output

Program output.

...o.s.cache.interceptor.CacheInterceptor   : No cache entry for key '1' in cache(s) [employeeCache]
...c.howtodoinjava.service.EmployeeService  : Getting employee from DB
...c.h.caching.CustomCacheEventLogger       : Cache event = CREATED, Key = 1,  Old value = null, New value = Employee(id=1, firstName=Alex, lastName=Gussin)

...o.s.cache.interceptor.CacheInterceptor   : Cache entry for key '1' found in cache 'employeeCache'

...org.ehcache.core.EhcacheManager          : Cache 'employeeCache' removed from EhcacheManager.

Drop me your questions related to this Spring boot cache example using Ehcache 3 in the comments.

Happy Learning !!

Source Code on Github


Notify of
Most Voted
Newest Oldest
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

Dark Mode

Dark Mode