在多个模块中使用Spring缓存注释

Sne*_*kse 31 spring caching annotations ehcache spring-annotations

我有一个util模块,可以生成一个可以在其他应用程序中使用的jar.我希望这个模块使用缓存,并且更喜欢使用Spring的annotation-driven缓存.

所以Util-Module会有这样的事情:


DataManager.java

...
@Cacheable(cacheName="getDataCache")
public DataObject getData(String key) { ... }
...
Run Code Online (Sandbox Code Playgroud)

数据管理器 - ehcache.xml中

...
<cache name="getDataCache" maxElementsInMemory="100" eternal="true" />
...
Run Code Online (Sandbox Code Playgroud)

数据管理器弹簧-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"/>
...
Run Code Online (Sandbox Code Playgroud)

我还希望我的可部署单元通过Spring注释进行缓存,同时将上面的jar包含为依赖项.所以我Deployable-Unit会有这样的事情:


MyApp.java

...
@Cacheable(cacheName="getMyAppObjectCache")
public MyAppObject getMyAppObject(String key) { ... }
...
Run Code Online (Sandbox Code Playgroud)

我-APP-ehcache.xml中

...
<cache name="getMyAppObjectCache" maxElementsInMemory="100" eternal="true" />
...
Run Code Online (Sandbox Code Playgroud)

我的应用程序内弹簧-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"/>
...
Run Code Online (Sandbox Code Playgroud)

题:

是否可以在主项目和依赖模块中使用注释驱动的缓存,同时保持配置分离?

如果没有,将不胜感激地说明原因.如果是这样,将理解上述配置中需要改变的内容的解释.

Nic*_*rts 13

使用此类:http://static.springsource.org/autorepo/docs/spring/3.2.0.M1/api/org/springframework/cache/support/CompositeCacheManager.html, 如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)


小智 9

这似乎在3.2M1中修复,请参阅https://jira.springsource.org/browse/SPR-8696


Joe*_*Joe 5

Spring目前期望cacheManager是Singleton.这是ehcache-spring-annotations项目遇到的问题,我还没有看到请求得到满足. http://code.google.com/p/ehcache-spring-annotations/issues/detail?id=76

与Java和Spring一样,您可以选择重新实现该类.

http://forums.terracotta.org/forums/posts/list/5618.page#27960提供了一些基础解释,说明了一些人提出的解决方法和解决方法.

是他们提出的实际代码.该方法确实创建了一个遵循的约定,但如果您不喜欢所描述的实际方法,则可以很容易地使用您自己的版本重新实现它.