---
title: "Spring3.1 Cache注解"
author: "Fred_Han"
date: "2013-03-07T10:37:51Z"
tags: []
categories: ["Web前端"]
slug: "spring3-1-cache"
draft: false
lastmod: "2013-03-07T10:37:51Z"
id: 1825344
url: "https://fred-han.iteye.com/blog/1825344"
---

### [Spring3.1 Cache注解](http://hanqunfeng.iteye.com/blog/1158824)

**博客分类：**

- [Spring](http://hanqunfeng.iteye.com/category/96012)

[spring](http://www.iteye.com/blogs/tag/spring)[ehcache](http://www.iteye.com/blogs/tag/ehcache)

需要感慨一下，spring3.0时丢弃了2.5时的spring-modules-cache.jar，致使无法使用spring来方便的管理cache注解，好在3.1.M1中增加了对cache注解的支持，可喜可贺啊！

 

希望了解spring2.5的cache注解，可以参考如下内容：

### [Spring基于注解的缓存配置--EHCache AND OSCache](http://hanqunfeng.iteye.com/blog/603719)

### [Spring基于注解的缓存配置--web应用实例](http://hanqunfeng.iteye.com/blog/605123)

2.5时，spring没有自己的解决方案，都是采用对许多第三方cache框架的支持，比如EHCache和OSCache等等，不过到了3.1，spring就只提供EHCache的支持了，不过spring3.1还给出了自己的解决方案。

 

下面简单介绍一下spring3.1.M1中的cache功能。

spring3.1.M1中负责cache的模块是org.springframework.context-3.1.0.M1.jar

 

与2.5时的modules模块类似，3.1的注解缓存也是在方法上声明注解，3.1同样提供了两个注解：

@Cacheable：负责将方法的返回值加入到缓存中

@CacheEvict：负责清除缓存

 

**@Cacheable** 支持如下几个参数：

value：缓存位置名称，不能为空，如果使用EHCache，就是ehcache.xml中声明的cache的name

key：缓存的key，默认为空，既表示使用方法的参数类型及参数值作为key，支持SpEL

condition：触发条件，只有满足条件的情况才会加入缓存，默认为空，既表示全部都加入缓存，支持SpEL

 

例如：

Java代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

01. //将缓存保存进andCache，并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key
02. @Cacheable(value="andCache",key="#userId + 'findById'")
03. public SystemUser findById(String userId) {
04. SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);
05. return user ;
06. }
07. //将缓存保存进andCache，并当参数userId的长度小于32时才保存进缓存，默认使用参数值及类型作为缓存的key
08. @Cacheable(value="andCache",condition="#userId.length &lt; 32")
09. public boolean isReserved(String userId) {
10. System.out.println("hello andCache"+userId);
11. return false;
12. }

 

 

**@CacheEvict** 支持如下几个参数：

value：缓存位置名称，不能为空，同上

key：缓存的key，默认为空，同上

condition：触发条件，只有满足条件的情况才会清除缓存，默认为空，支持SpEL

allEntries：true表示清除value中的全部缓存，默认为false

 

例如：

Java代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

01. //清除掉指定key的缓存
02. @CacheEvict(value="andCache",key="#user.userId + 'findById'")
03. public void modifyUserRole(SystemUser user) {
04. System.out.println("hello andCache delete"+user.getUserId());
05. }
06. //清除掉全部缓存
07. @CacheEvict(value="andCache",allEntries=true)
08. public final void setReservedUsers(String\[] reservedUsers) {
09. System.out.println("hello andCache deleteall");
10. }

 

**一般来说，我们的更新操作只需要刷新缓存中某一个值，所以定义缓存的key值的方式就很重要，最好是能够唯一，因为这样可以准确的清除掉特定的缓存，而不会影响到其它缓存值** ，

**比如我这里针对用户的操作，使用(userId+方法名称)的方式设定key值** ，**当然，你也可以找到更适合自己的方式去设定。**

 

**SpEL：Spring Expression Language**

关于SpEL的介绍，可以参考如下地址：

http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/expressions.html

 

 

了解了cache的注解之后，接下来说说如何使注解生效，其实就是需要在spring的配置文件中增加一些配置。

 

**1.spring-cache**

首先我们来看一下如何使用spring3.1自己的cache，

需要在命名空间中增加cache的配置

Xml代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

1. &lt;beans xmlns="http://www.springframework.org/schema/beans"
2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
3. xmlns:cache="http://www.springframework.org/schema/cache"
4. xsi:schemaLocation="
5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
6. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"&gt;

 

之后添加如下声明：

Xml代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

01. &lt;!-- 启用缓存注解功能，这个是必须的，否则注解不会生效，另外，该注解一定要声明在spring主配置文件中才会生效 --&gt;
02. &lt;cache:annotation-driven cache-manager="cacheManager"/&gt;
03. &lt;!-- spring自己的换管理器，这里定义了两个缓存位置名称 ，既注解中的value --&gt;
04. &lt;bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"&gt;
05. &lt;property name="caches"&gt;
06. &lt;set&gt;
07. &lt;bean
08. class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"
09. p:name="default" /&gt;
10. &lt;bean
11. class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"
12. p:name="andCache" /&gt;
13. &lt;/set&gt;
14. &lt;/property&gt;
15. &lt;/bean&gt;

 

**2.spring-ehcache**

接下来说说对ehcache的支持，其实只需要把cacheManager换成EHCache的cacheManager即可，如下：

Xml代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

1. &lt;!-- 启用缓存注解功能，这个是必须的，否则注解不会生效，另外，该注解一定要声明在spring主配置文件中才会生效 --&gt;
2. &lt;cache:annotation-driven cache-manager="cacheManager"/&gt;
3. &lt;!-- cacheManager工厂类，指定ehcache.xml的位置 --&gt;
4. &lt;bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
5. p:configLocation="classpath:/config/ehcache.xml" /&gt;
6. &lt;!-- 声明cacheManager --&gt;
7. &lt;bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
8. p:cacheManager-ref="cacheManagerFactory" /&gt;

 

 

 **ehcache.xml**

Xml代码  [![收藏代码](http://hanqunfeng.iteye.com/images/icon_star.png)]()

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03. xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
04. monitoring="autodetect"&gt;
05. &lt;!--
06. &lt;diskStore path="java.io.tmpdir" /&gt; --&gt;
07. &lt;diskStore path="E:/cachetmpdir"/&gt;
08. &lt;defaultCache maxElementsInMemory="10000" eternal="false"
09. timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
10. maxElementsOnDisk="10000000" diskPersistent="false"
11. diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /&gt;
12. &lt;cache name="andCache" maxElementsInMemory="10000"
13. maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
14. diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600"
15. memoryStoreEvictionPolicy="LFU" /&gt;
16. &lt;/ehcache&gt;

 

 

ok，这样注解缓存就生效了。

转自：http://hanqunfeng.iteye.com/blog/1158824