參考:https://blog.csdn.net/chinabestchina/article/details/78009220
1. pom文件
<!-- 除了spring core/beans/context 等宣羊,必須要引入的依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
2. spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!--開啟緩存注解-->
<cache:annotation-driven/>
<!-- 掃描包路徑 -->
<context:component-scan base-package="com.test.dao"/>
<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager">
<property name="cacheSpecification" value="expireAfterWrite=3600s"/>
<property name="cacheNames">
<list>
<value>myCache</value>
</list>
</property>
</bean>
</beans>
3. 使用
package com.test.dao;
public interface DemoMapper {
@Cacheable(value = "myCache", key = "#p0.name + '_' + #p0.age", unless="#result == null")
DemoVo queryDemo(Request request);
}
注意:在接口上使用注解時(shí)把篓,必須使用 #p0
#p1
等取參數(shù),使用參數(shù)名(#request
)無法取到屬性值疾渣,會(huì)報(bào)錯(cuò)。普通類里的方法兩種都可以路星。
unless="#result == null"
表示結(jié)果為空時(shí)不緩存诱桂。