繁体   English   中英

我可以在没有注释的情况下使用Spring的缓存功能吗?

[英]Can I use Spring's caching features without the annotations?

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

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

我打算提供一个类路径bean文件和类路径eh-cache配置,以提供功能,而无需使用项目就知道我的实现的内部以及需要缓存的方法(其中许多方法永远不会直接访问)。

但是,阅读在多个模块中使用Spring缓存注释的问题及其答案显然会引起问题,因为任何正在使用的项目也都使用Spring缓存注释。 我希望如果没有与注释匹配的已声明缓存,Sprint会静默失败,但是失败并显示以下错误:

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

导致我得出的结论是我不能使用缓存注释(这与我的原始结论冲突: 是否可以使用多个ehcache.xml(在不同项目中,相同的战争)?我的测试对此进行了支持。

因此: 是否可以与实现类分开声明缓存,最好在xml中声明? 这将使我能够准备具有缓存规则的其他文件,并使用标准的spring属性替换来替换缓存管理器名称(我已经对数据源进行了类似的操作)? 不幸的是, 参考文档仅描述了基于注释的配置。

您可以使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM