Caching in Spring Example + Ehcache + Cacheable + Annotation/JavaConfig

author-image   By Dhiraj,   25 November, 2016 10K

As we know EhCache is a widely used caching library. Spring provides easy annotation based integration mechanism of ehcache using @Cacheable. Here we will be creating a sample example to integrate Ehcache with spring by using @Cacheable annotation.We will be caching user details and try to fetch the same user detail again and again and compare the time required to fetch it. The spring configuration here in the app will be completely java config.

Environment Setup

1. JDK 8 2. Spring 4 3. Intellij Idea/ eclipse 4. Maven

Project Structure


Maven Dependencies

Following are the maven dependencies required for spring ehcache implementation.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""





Spring Bean Configuration

Now let us configure our beans.

@EnableCaching : Enables Spring's annotation-driven cache management capability. If no config location is specified, a CacheManager will be configured from "ehcache.xml" in the root of the class path (that is, default EhCache initialization - as defined in the EhCache docs - will apply).

CacheManager : Allows for retrieving named Cache regions.
package com.developerstack.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan(basePackages = "com.developerstack")
public class BeanConfig {

	public CacheManager cacheManager() {
		return new EhCacheCacheManager(ehCacheCacheManager().getObject());

	public EhCacheManagerFactoryBean ehCacheCacheManager() {
		EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
		cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
		return cmfb;
 Other Interesting Posts
Spring 5 Features and Enhancements
Spring Hibernate Integration with complete JavaConfig
Spring MVC Angularjs Integration with complete JavaConfig
Spring Boot Spring MVC Example
Spring Boot Thymeleaf Example
Spring Boot Security Redirect after Login with complete JavaConfig
Spring Security Hibernate Example with complete JavaConfig
Securing REST API with Spring Security Basic Authentication
Spring Security Password Encoding using Bcrypt Encoder
Spring Boot Security Custom Form Login Example
Spring JMS Activemq Integration with Spring Boot
Websocket spring Boot Integration without STOMP with complete JavaConfig
Spring Junit Integration with complete JavaConfig
Spring Ehcache Cacheable Example with complete javaConfig

Following is the model class to hold user details.
package com.developerstack.model;

public class UserDetails {
	private int id;
	private String firstName;
	private String lastName;
	private String email;
	public String getId() {
		return id;
	public void setId(String id) { = id;
	public String getFirstName() {
		return firstName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	public String getLastName() {
		return lastName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	public String getEmail() {
		return email;
	public void setEmail(String email) { = email;


Let us define our service. Here we are caching the userDetails object. The value user is the same as we defined have defined in our ehcache.xml.
package com.developerstack.service.impl;

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

import com.developerstack.model.UserDetails;
import com.developerstack.service.UserService;

public class UserServiceImpl implements UserService {

	@Cacheable(value="user", key="#id")
	public UserDetails findUser(long id) {
		UserDetails ud1 = new UserDetails();
		return ud1;

	private void pause(long sec) {
		try {
		} catch (InterruptedException e) {


Below is the ehcache.xml. This file has the cache configuration.

<ehcache xmlns:xsi=""

	<diskStore path="" />

	<cache name="user"
		timeToIdleSeconds="300" timeToLiveSeconds="600"
		<persistence strategy="localTempSwap" />


Now let us create which will execute the service to test whether our caching implementation is working as expected or not. Here we will be calling the same method of the service class with same and different parameters and analyse the time required to execute the methods. based on this we will draw our conclusion on the behaviour of caching.
package com.developerstack.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.developerstack.service.UserService;

public class Application {

	public static void main(String[] args) {

		ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
		UserService obj = context.getBean("userService", UserService.class);
		long initialMillis = System.currentTimeMillis();
		long currentMillis = System.currentTimeMillis();
		System.out.println("Time taken to fetch user for first time " + (currentMillis - initialMillis)/1000 + " sec");
		System.out.println("*************finding user for second time ****************************");
		initialMillis = System.currentTimeMillis();
		currentMillis = System.currentTimeMillis();
		System.out.println("Time taken to fetch same user again " + (currentMillis - initialMillis)/1000 + " sec");
		System.out.println("*************finding new user ****************************");
		initialMillis = System.currentTimeMillis();
		currentMillis = System.currentTimeMillis();
		System.out.println("Time taken to fetch another user " + (currentMillis - initialMillis)/1000 + " sec");
		((ConfigurableApplicationContext) context).close();


Run Application

1. Run as a java application. And analyse the console output. For the first time, the method took 3 seconds to find and return the user object. At this point the output is cached with key id. When we again tried to find user with same id, the method did not execute and the user object was returned from cache and hence it took 0 sec to find the user. Next, we again invoked the method with different id, but this time since the user with id 2 is not cached, the mmethod executed and tok 3 seconds to find and return the user object.



I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source

If You Appreciate This, You Can Consider:

  • Like us at: Facebook or follow us at Twitter
  • Share this article on social media or with your teammates.
  • We are thankful for your never ending support.

About The Author


I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.

Further Reading on Spring MVC

1 Spring Boot Mvc Example

2 Spring Websocket Integration Example Without Stomp

3 Spring Jms Activemq Integration Example

4 Spring Mvc Angularjs Integration Example

5 Writing Junit Tests In Spring4 Mvc

6 Spring Hibernate Integration Example Javaconfig