欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-24 18:58:34
...

最近使用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>