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>
推荐阅读
-
详解 Spring注解的(List&Map)特殊注入功能
-
详解 Spring注解的(List&Map)特殊注入功能
-
spring注解在自定义jar包中无法被扫描的解决方案
-
基于注解的Spring的AOP功能演示
-
FeignClient原理解析,100行代码实现feign功能,mybatis的mapper、dubbo、feign实现原理模拟。spring扫描自定义注解原理。Javassist实现动态代理原理
-
spring-data-elasticsearch @Field注解无效的完美解决方案
-
@PathVariable注解,让spring支持参数带值功能的案例
-
struts2 hibernate spring注解的整合(重写了巴巴运动网部门功能)
-
struts2 hibernate spring注解的整合(重写了巴巴运动网部门功能)
-
spring结合mysql事务注解@Transactional不起作用的有关问题