Cache注解

来源:互联网 发布:太平人寿内勤知乎 编辑:程序博客网 时间:2024/06/06 14:18

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


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

@CacheEvict 支持如下几个参数:

value:缓存位置名称,不能为空,同上

key:缓存的key,默认为空,同上

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

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

//清除掉指定key的缓存@CacheEvict(value="andCache",key="#user.userId + 'findById'")public void modifyUserRole(SystemUser user) {         System.out.println("hello andCache delete"+user.getUserId());}//清除掉全部缓存@CacheEvict(value="andCache",allEntries=true)public void setReservedUsers() {System.out.println("hello andCache deleteall");}

xml:

       <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 --><cache:annotation-driven cache-manager="cacheManager"/><!-- spring自己的换管理器,这里定义了两个缓存位置名称 ,既注解中的value --><bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"><property name="caches"><set><beanclass="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"p:name="default" /><beanclass="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean"p:name="andCache" /></set></property></bean> 


0 0
原创粉丝点击