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

标签 spring caching configuration annotations ehcache

我正在开发一个我计划使用的模块 Spring's declarative caching处理。我用缓存写了很多方法

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

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

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

java.lang.IllegalArgumentException: Cannot find cache named [businessUnitCache] for CacheableOperation[public



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

所以:是否可以将缓存与实现类分开声明,最好是在 xml 中? 这将允许我准备一个带有缓存规则的附加文件,并使用标准 Spring 属性替换替换缓存管理器名称(我已经在对数据源做类似的事情)?不幸的是 refernece documentation仅描述基于注释的配置。

最佳答案

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

关于spring - 我可以在没有注释的情况下使用 Spring 的缓存功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11854328/

相关文章:

database - General/Phalcon - ACL 和数据库存储

java - 为 Spring Data 运行的每个查询设置注释

java - 如何在具有多个配置文件的基于注释的配置中设置bean加载顺序?

java - 使用 mvn exec :java 执行 spring 应用程序

java - 无法在 JavaMail 中设置文本和添加附件

c - 硬盘驱动器盘上读取缓存

ios - NSURLCache 问题 - 图像从缓存中释放?

javascript - 如何在javascript中访问 flask 配置?

javascript - 在 Node.js、React.js 和 Python 应用程序之间共享配置

c# - 使用不同的 publicKeyToken 升级引用 .Net dll