4

我正在开发一个模块,我计划使用Spring 的声明式缓存来处理。我用缓存写了很多方法

@Override
@Cacheable("businessUnitCache")
public BusinessUnit getBusinessUnit(String businessUnitId){

我计划提供一个类路径 bean 文件和类路径eh-cache 配置来提供功能,而无需使用项目来了解我的实现的内部结构以及需要缓存哪些方法(其中许多方法他们永远不会直接访问)。

但是,阅读在多个模块中使用 Spring 缓存注释的问题及其答案,这显然会导致一个问题,即任何消费项目也使用 Spring 缓存注释。如果没有声明的缓存与注释匹配,我希望 Sprint 会静默失败,但它会失败并出现错误:

java.lang.IllegalArgumentException:找不到缓存名为 [businessUnitCache] 用于 CacheableOperation [public

让我得出结论,我不能使用缓存注释(这与我从问题Is it possible to use multiple ehcache.xml (in different projects, same war)? 中得出的原始结论相冲突? 。我的测试支持了这一点。

那么:是否可以将缓存与实现类分开声明,最好是在 xml 中? 这将允许我使用缓存规则准备一个附加文件,并使用标准弹簧属性替换替换缓存管理器名称(我已经在对数据源进行类似的操作)?不幸的是,参考文档仅描述了基于注释的配置。

4

1 回答 1

3

您可以使用 xml 文件配置缓存,请参阅 spring 参考手册:

http://static.springsource.org/spring/docs/current/spring-framework-reference/html/cache.html#cache-declarative-xml

<!-- the service we want to make cacheable -->
<bean id="bookService" class="x.y.service.DefaultBookService"/>

<!-- cache definitions -->
<cache:advice id="cacheAdvice" cache-manager="cacheManager">
<cache:caching cache="books">
    <cache:cacheable method="findBook" key="#isbn"/>
    <cache:cache-evict method="loadBooks" all-entries="true"/>
</cache:caching>
</cache:advice>  

<!-- apply the cacheable behaviour to all BookService interfaces -->
<aop:config>
<aop:advisor advice-ref="cacheAdvice" pointcut="execution(* x.y.BookService.*(..))"/>
</aop:config>
于 2012-08-08T09:46:40.707 回答