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 Goyello. Open source enthusiast, team leader, teacher, blogger and Twitter user @kolorobot

  • hussainanjar

    Really nice article …. easy to read and understand.

  • Thanks a lot!

  • Pingback: Blog bookmarks 08/10/2010 « My Diigo bookmarks()

  • rborowiec

    Thx a lot!

  • Great article. I’m one of the authors of the ehcache-spring-annotations library and appreciate the great writeup.


  • Anonymous

    Thank you!

  • Pingback: Cachés y Spring « Java Mania()

  • Pingback: EhCache Upgrade: A Farewell to Spring Modules « A Technical Discourse()

  • Anonymous

    I followed all the steps mentioned above but it doesn’t seem to work. I do not see any ‘Initialised cache: ‘ message. My log4j level is set to INFO.
    Don’t I need to set ‘hibernate.cache.use_second_level_cache’ to true in application-context.xml and set values for ‘hibernate.cache.provider_class’?

  • Anonymous

    No, you don’t need hibernate cache provider, because this is not hibernate cache. Checkout demo project attached to the post, you will find all the configuration there.

  • Rathinasamy R.S.

    I’ve used this project in tomcat without any error but when moving it to
    virgo web server got some error that is web application failed to
    start, how to resolve this plz help me 

  • Anonymous

    I build projects usually on Tomcat server. Unfortunately, I don’t know Virgo and I never used it. So I think I cannot help you here. I am really sorry.

  • Pingback: Cache Spring JDBC template using ehcache annotations « Thomsun's Blog()

  • Balaji Rengan

     Great Article. Explained in very clear fashion. It worked the first time like Magic. Thank you very much.

  • Great article.That was what I was searching for…

  • Srinivas V

    Could you provide the complete project

  • abhijit choudhury

    When selfPopulating=”true” for @Cacheable and ehcache:annotation-driven settings have self-populating-cache-scope=”method” It creates different instances for each annotated method. How do I use @TriggersRemove to remove the item from its respective cache instance

  • Pingback: EhCache Upgrade: A Farewell to Spring Modules « A Technical Discourse()

  • Pingback: Skype and Agile software development were really hot on our blog this year()

  • I have downloaded above project and executed as it is ,

    It seems need to modify the config,

    First calll to – http://localhost:8080/esa/message.html,
    it shows below output

    DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key ‘183410223502399’ for invocation: ReflectiveMethodInvocation:
     public abstract com.goyello.esa.model.Message; target is of class [

    Then click id – 1 to view message – It shows below message
    DEBUG []: == find message by id=1
    DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key ‘167334053963’ for invocation: ReflectiveMethodInvocation: pu
    blic abstract java.util.Collection; target is of class [

    Click viewALL to see list of message – below o/p is shown
    DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key ‘183410223502399’ for invocation: ReflectiveMethodInvocation:
     public abstract com.goyello.esa.model.Message; target is of class [

    BUT again calling to id – 1 why below o/p is shown, data should retrieve from cache ??
    so it means it is not caching data..
    DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key ‘167334053963’ for invocation: ReflectiveMethodInvocation: pu
    blic abstract java.util.Collection; target is of class [

  • proximuSs

    Very nice article/tutorial – u click once and it’s running … unlike so many others…n/c

  • Joe Bull

    If you want to use gradle instead of maven, just put the following into a build.gradle file and import:
    apply plugin: ‘java’
    apply plugin: ‘eclipse’

    repositories {

    dependencies {

    compile ‘org.springframework:spring-webmvc:3.2.3.RELEASE’
    compile ‘org.springframework:spring-web:3.2.3.RELEASE’
    compile ‘org.springframework:spring-context:3.2.3.RELEASE’
    compile ‘org.springframework:spring-context-support:3.2.3.RELEASE’
    compile ‘com.googlecode.ehcache-spring-annotations:ehcache-spring-annotations:1.2.0’
    compile ‘org.slf4j:slf4j-log4j12:1.6.1’
    testCompile ‘org.mockito:mockito-all:1.9.5’
    testCompile ‘junit:junit:4.11’
    testCompile ‘org.springframework:spring-test:3.2.3.RELEASE’

  • Pingback: You fancy a bit of EhCaching in Spring, but can’t find class EhCacheManagerFactoryBean? | The Tai-Dev Blog()

  • Pingback: EhCache and Spring – can’t find class EhCacheManagerFactoryBean? | 碎碎CodVying()

  • Pingback: 基于Spring和Ehcache 注解式的服务器端数据缓存 | 雪谛.轶微()

  • zhouhao

    Great article!