简体   繁体   中英

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

I'm developing a module I was planning on using Spring's declarative caching to handle. I wrote a number of methods using the cache

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

I was planning to provide a classpath beans file and classpath eh-cache configuration to provide the functionality without requiring consuming projects to know the internals of my implementation and which methods need to be cached (many of these methods they'd never access directly ).

However, reading the question Using Spring cache annotation in multiple modules and it's answers this is obviously going to cause a problem is any of the consuming projects use Spring cache annotations as well. I was hopeful that Sprint would fail silently if there was no declared cache matching an annotation, but it fails with the error:

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

Leading me to the conclusion I can't use the cache annotations (which conflicts with my original conclusion from the question Is it possible to use multiple ehcache.xml (in different projects, same war)? . My testing backs this up.

So: Is it possible to declare the caching separately from the implementation classes, preferably in xml? This would allow me to prepare an additional file with the caching rules, and replace the cache manager name using standard spring property replacement (I'm already doing something similar with the datasource)? Unfortunately the refernece documentation only describes the annotation based configuration.

you can configure the cache using the xml file, see the spring reference manual:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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