MathJax

SyntaxHighlighter

Highlight

Custom CSS

Sunday, October 22, 2006

Configuring EhCache with Spring

There is a tricky point to configuring EhCache with Spring, which I discovered earlier last week. Usually you configure EhCache with by overriding the default ehcache.xml, defining the disk store location, cache name, and various other cache properties. However, if you use Spring's EhCacheFactoryBean and/or EhCacheManagerFactoryBean to build your cache, you will be in for a surprise.

If you use the EhCacheManagerFactoryBean and specify an ehcache.xml file, the only property that will be used is the diskStorePath property; the rest of the cache properties specified in your xml configuration file will be ignored. You must use setter injection to set these properties via a EhCacheFactoryBean . However, there is no way to set the diskStorePath property using setter injection. You can try, but the property you inject will not be used.

<bean id="myCacheBean"
    class="org.springframework.cache.ehcache.EhCacheFactoryBean">
  <!-- This property is totally ignored! -->                              
  <property name="diskStorePath"                                             
      value="java.io.tmpdir/myCacheName"/>                                   
</bean>

This is because the CacheManager will automatically override any diskStorePath you have set when you add a new cache to the manager:

// Code snippet from Cache.java in the EhCache project:                         
/**
 * @param diskStorePath this parameter is ignored. CacheManager
 * sets it using setter injection.                                              
 */

The solution? Unfortunately, I don't know of any except to use both an ehcache.xml configuration file and setter injection in spring to override the defaults.
Post a Comment