我可以在不使用注解的情况下使用Spring的缓存功能吗?

4

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

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

我计划提供一个classpath beans文件和classpath eh-cache配置,以提供功能,而不需要消费项目了解我的实现内部和哪些方法需要缓存(其中许多方法他们永远不会直接访问)。
然而,阅读问题在多个模块中使用Spring cache注释及其答案后,显然会导致问题,如果任何消费项目也使用Spring缓存注释。我希望Sprint如果没有声明的缓存匹配注释,则会静默失败,但它会因以下错误而失败:
java.lang.IllegalArgumentException:无法为CacheableOperation [public]找到名称为[businessUnitCache]的缓存
这使我得出结论,我不能使用缓存注释(这与我从问题是否可以在不同的项目中使用多个ehcache.xml(同一war)?的最初结论相冲突)。我的测试支持这一点。

所以: 是否可以将缓存声明与实现类分开,最好在xml中? 这将允许我准备一个额外的文件,并使用标准spring属性替换(我已经在数据源上做了类似的事情)来替换缓存管理器名称。不幸的是, 参考文档 只描述了基于注释的配置。

1个回答

2
你可以使用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/版本会有所帮助,但不幸的是,谷歌通常不会将您链接到那里。 - C. Ross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接