How to profit from the new Ehcache Annotations for Spring? As a Java developer you would like to know, don’t you? ehcache-spring-annotations – licensed under the Apache License, Version 2.0 – is a project that simplifies caching in Spring based application using popular Ehcache library. Version 1.1.2 of ehcache-spring-annotations has been released only recently. In this article I will present how to create a web project that benefits from ehcache-spring-annotations

Create a new web project

For the showcase, a Spring MVC based web project will be used. If you use Eclipse make sure you have m2eclipse installed, then create a Maven project using JEE 5 web application archetype (group id: org.codehaus.mojo.archetypes, artifact id: webapp-jee5): wtp The above archetype works perfectly with Eclipse 3.6.

Project structure

I created a simple web project that consists of one controller: MessageController:

The above controller depends on MessageStorage, simple DAO, that is defined as follows:

The only implementation of MessageStorage is MemoryMessageStorage:

Whit the minimum dependencies presented below we are able to run the application (See Download section to get complete application).

Introducing Ehcache Annotations for Spring to the web project

Now it’s time to add caching capabilities to the application. We provide caching to MemoryMessageStorage. First of all, add the required dependencies to the POM: Ehcache Annotations for Spring dependency:

As of time of writing there was version 2.2.0 of Ehcache available. But we use version 2.1.0 that Ehcache Annotations for Spring 1.1.2 depends on. I also added SLF API implementation:

With the above dependencies we are able to use Ehcache Annotations for Spring. We add the annotations to MemoryMessageStorage as mentioned before. There are a few simple rules:

  • use cache with name “messageCache” for caching messages for invocations of findMessage(long)
  • use cache with name “messagesCache” for caching messages for invocations of findAllMessages()
  • remove all elements from “messagesCache” after the invocation of addMessage(Message)

To achieve the above we use @Cachable and @TriggersRemove annotations aspresented below:

Spring and Ehcache configuration

Having annotations in place, we need to configure the application to use them. This is done via Spring configuration file:

The last thing to do is to add the Ehcache configuration. Create file named ehcache.xml and place it in /WEB-INF folder of web application:

Configure cache manager so that it uses Ehcache configuration. To do so, add configLocation property to cacheManager bean in Spring context file:

The configuration is done. Run the application on Tomcat 6 server (Run As – Run on server) and observe log output – if DEBUG is enabled you will find similar entries: DEBUG [net.sf.ehcache.Cache]: Initialised cache: messagesCache DEBUG [net.sf.ehcache.Cache]: Initialised cache: messageCache Do some interactions with the application to observe the caching behavior (make sure DEBUG log level is enabled). The actions are (to see XML output replace “html” with “xml”):

  • get the list of all messages – http://localhost:8080/esa/message.html
  • get a message by id – http://localhost:8080/esa/message/{id}.html
  • add a new message (from) – http://localhost:8080/esa/message/add.html

If you execute getMessages() of MessageController for the first time you should see: DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key '167334053963' for invocation: ReflectiveMethodInvocation: public abstract java.util.Collection; target is of class [] DEBUG []: == got all messages, size=5 While invoking the same method for the second time, the second line from the above log output is gone, because the collection of all messages was retrieved from the cache. To remove cache from the messages in a simple way call addMessage() of MessageController. Then repeat previous steps to make sure the cache was cleared properly.

Unit testing

To be sure that the caching works without reading the log files we create unit tests for caching. For this tutorial we modify the MessageStorage interface and we add void setDelegate(MessageStorage storageDelegate) method to it. The given delegate will be used to check if the caching actually works. The implementation class changes are (for all other methods similarly):

To make the testing easier we use two more dependencies: Spring Test and Mockito:

The test class will run with SpringJUnit4ClassRunner:

The delegate is a mock object that is used for checking the real number of invocations on a MessageStorage. The Spring context for test looks like this:

Now we are ready to run the created test to verify the actual invocations on MemoryMessageStorage. Results we wish to see: test

The summary

Using Ehcache Spring Annotations is straightforward. With a couple of simple steps you may introduce caching in your application. I strongly suggest that before using the library in live project you visit the project website and read the documentation to be aware of other functionalities not covered in this article.

Update: Spring 3.1 release, among many enhancements, brings native support for method caching with so-called cache abstraction. To read more about this feature check Quick start with method caching using Spring 3.1 and Ehcache follow-up post.


Ehcache Spring Annotations project page – Ehcache project page – Spring 3.0 reference – Mockito – Maven2 –

Download and run the project

The complete project can be downloaded here: demo-project After you download the file, unpack it, navigate to the project folder and run following command (maven2 needs to be installed): mvn clean tomcat:run Then navigate to you browser to see the working application:

Development Manager and Java Developer at Aspire Systems Poland. Open source enthusiast, team leader, teacher, blogger and Twitter user @kolorobot