spring 启动缓存注解

1、

spring配置文件 applicationContext.xml 需要注意添加红色斜体部分配置

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

<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="ehcacheManager"/>
<!-- cacheManager工厂类,指定ehcache.xml的位置 -->
<bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<!-- 声明cacheManager -->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcacheManagerFactory" />
</bean>


2、在service层增加注解配置

@Cacheable

Cache a method call. In the following example, the value is the return type, a Manual. The key is extracted from the ISBN argument using the id.

@org.springframework.cache.annotation.Cacheable(value="QY_api_productTop",
 key="#isbn.id") 
public Manual findManual(ISBN isbn, boolean checkWarehouse)

  key="#isbn.id"  对象缓存的key值,需要保证唯一,用的是Spring的 SpEL表达式, 取值为 isbn对象的id属性值

  value="QY_api_productTop":指的是ehcache.xml里的缓存名字

还支持条件condition,包括 属性 id<10,如下:

@Cacheable(value = "QY_api_productTop",key="#isbn.id",condition = "#isbn.id<10")
public Manual findManual(ISBN isbn, boolean checkWarehouse)

  

@CacheEvict 

Clears the cache when called.   清除QY_api_productTop缓存中所有对象

@org.springframework.cache.annotation.CacheEvict(value = "QY_api_productTop",
 allEntries=true) 
public void loadManuals(Long id)


可以清除指定对象的缓存例如:

@CacheEvict(value = "QY_api_productTop", key = "#id")
public void loadManuals(Long id)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值