Spring cache 注解功能不起作用的解决方案

最近使用spring的cache模块来加速程序,写了很多注解,如: @Cacheable/@CachePut/@CacheEvict/@Caching

发现这些注解根本不起作用啊。赶紧跑去看了看spring的文档,发现缺失了下面内容:

<cache:annotation-driven/> 

之后我的配置文件如下:

	
<!-- cache start -->
	<cache:annotation-driven cache-manager="cacheManager"/> 
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
		p:cache-manager-ref="ehcache" />

	<!-- EhCache spring library setup -->
	<bean id="ehcache"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
		p:configLocation="classpath:${dmap.console.cache.file}" p:shared="true" />

	<!-- cache end -->

参考下面xml添加上cache的schema

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

        <cache:annotation-driven />

</beans>

 经过添加 <cache:annotation-driven cache-manager="cacheManager"/> 之后我的cache注解能用了。 

spring的原文如下:

30.3.6 Enable caching annotations

It is important to note that even though declaring the cache annotations does not automatically trigger their actions - like many things in Spring, the feature has to be declaratively enabled (which means if you ever suspect caching is to blame, you can disable it by removing only one configuration line rather than all the annotations in your code).

To enable caching annotations add the annotation @EnableCaching to one of your @Configuration classes:

@Configuration
@EnableCaching
public class AppConfig {
}

Alternatively for XML configuration use the cache:annotation-driven element:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

        <cache:annotation-driven />

</beans>

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/2209257