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)