Posts Tagged ‘ehcache’

Spring Ehcache Integration

February 26th, 2009 20 comments

In this post I will share how to cache method results using Ehcache and Spring AOP. This is based on the post

The first step is to add all the required jars to the project. At minimum, the following jars should be present:

Spring and related jars (using 2.5.6 version here):

  • spring-2.5.6.jar
  • commons-logging.jar
  • commons-collections.jar
  • aspectjrt.jar
  • aspectjweaver.jar
  • jsr250-api-1.0.jar

Ehcache and its dependencies (using version 1.5.0):

  • ehcache-1.5.0.jar
  • backport-util-concurrent-3.0.jar
  • jsr107cache-1.0.jar

For the sake of this post, I will be using a DemoService with a method whose results need to be cached.

import java.util.List;
public interface DemoService
	public List getCarTypes(String filter);

Here is a dummy implementation of the above service:

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

public class DemoServiceImpl implements DemoService

	public List getCarTypes(String filter)
		List carTypes = new ArrayList();
		carTypes.add("Sport Utility");
		return carTypes;

And the application context with bean scanning turned on:


The next step in the process is to add ehcache.xml to the classpath. Details on this configuration file can be found at Ehcache web site



Spring makes integration with Ehcache easy with EhCacheManagerFactoryBean and EhCacheFactoryBean classes. The EhCacheManagerFactoryBean provides access to Ehcache’s CacheManager and the EhCacheFactoryBean exposes caches defined in ehcache.xml.

To make use of these beans, lets add the following to the application context file:

The next step is to create an AOP Aspect that would provide caching transparently:


import javax.annotation.Resource;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

public class CacheAspect
	private Cache cache;
	public Object cacheCarTypes(ProceedingJoinPoint joinPoint) throws Throwable
		Object[] arguments = joinPoint.getArgs();
		String location = (String)arguments[0];
		Element element = cache.get(location);
		if(null == element)
			Object result = joinPoint.proceed();
			if(null != result)
				element = new Element(location, result);
		return element != null ? element.getValue() : null;

Finally, declare the newly created aspect in the application context file:

Spring Modules provides a great alternative for declarative caching with @Cacheable annotation. As of this post, Spring Modules is still in “draft” status.

You can download the source code used in this post here

Categories: Spring Tags: ,