【问题标题】:Can I use Spring's caching features without the annotations?我可以在没有注释的情况下使用 Spring 的缓存功能吗?
【发布时间】:2012-08-04 23:04:41
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

    标签: spring caching configuration annotations ehcache


    【解决方案1】:

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

    【讨论】:

    • 查看文档的/current/ 版本会有所帮助,但不幸的是,Google 通常不会将您链接到那里。
    猜你喜欢
    • 2019-10-27
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2015-04-13
    • 2016-11-14
    • 2021-05-18
    • 2013-08-17
    相关资源
    最近更新 更多