Using Spring cache annotation in multiple modules

Snekse picture Snekse · Dec 28, 2011 · Viewed 17.3k times · Source

I have a util module that produces a jar to be used in other applications. I'd like this module to use caching and would prefer to use Spring's annotation-driven caching.

So Util-Module would have something like this:


DataManager.java

...
@Cacheable(cacheName="getDataCache")
public DataObject getData(String key) { ... }
...

data-manager-ehcache.xml

...
<cache name="getDataCache" maxElementsInMemory="100" eternal="true" />
...

data-manager-spring-config.xml

...
<cache:annotation-driven cache-manager="data-manager-cacheManager" />
<!-- ???? --->
<bean id="data-manager-cacheManager" 
    class="org.springframework.cache.ehcache.EhcacheCacheManager" 
    p:cache-manager="data-manager-ehcache"/>
<bean id="data-manager-ehcache" 
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" 
    p:config-location="data-manager-ehcache.xml"/>
...

I would also like my deployable unit to have caching via Spring annotation, while including the above jar as a dependency. So my Deployable-Unit would have something like this:


MyApp.java

...
@Cacheable(cacheName="getMyAppObjectCache")
public MyAppObject getMyAppObject(String key) { ... }
...

my-app-ehcache.xml

...
<cache name="getMyAppObjectCache" maxElementsInMemory="100" eternal="true" />
...

my-app-spring-config.xml

...
<cache:annotation-driven cache-manager="my-app-cacheManager" />
<!-- ???? --->
<bean id="my-app-cacheManager" 
    class="org.springframework.cache.ehcache.EhcacheCacheManager" 
    p:cache-manager="my-app-ehcache"/>
<bean id="my-app-ehcache" 
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" 
    p:config-location="my-app-ehcache.xml"/>
...

Question:

Is it possible to use annotation driven caching in both your main project and a dependency module while keeping the configurations separated?

If not, an explanation of why it isn't would be appreciated. If so, an explanation of what needs to change in the above configuration would be appreciated.

Answer

Nicolas Mommaerts picture Nicolas Mommaerts · Feb 8, 2012

Use this class: http://static.springsource.org/autorepo/docs/spring/3.2.0.M1/api/org/springframework/cache/support/CompositeCacheManager.html like this:

<cache:annotation-driven cache-manager="cacheManager" />

<bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
    <property name="cacheManagers">
        <array>
            <ref bean="cacheManager1" />
            <ref bean="cacheManager2" />
        </array>
    </property>
    <property name="addNoOpCache" value="true" />
</bean>