配置 ehcacheContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
default-autowire="byName" default-init-method="init">
<!-- 在spring里配置cache就和在spring配置数据库一样, -->
<!-- 开启切面注解 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 缓存 属性-->
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<!-- 默认是cacheManager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
<!-- 支持缓存注解 -->
<cache:annotation-driven cache-manager="cacheManager" />
<cache:advice id="cacheAdvice" cache-manager="cacheManager">
<cache:caching cache="billingCache1">
<cache:cacheable method="query*" key="#root.methodName + #p0"/>
<cache:cache-evict method="delete*" all-entries="true"/>
<cache:cache-evict method="update*" all-entries="true"/>
</cache:caching>
</cache:advice>
<aop:config proxy-target-class="true">
<aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.mobile263.billing.service.*.*(..))"/>
</aop:config>
</beans>
Spring为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息。
属性名称 | 描述 | 示例 |
methodName | 当前方法名 | #root.methodName |
method | 当前方法 | #root.method.name |
target | 当前被调用的对象 | #root.target |
targetClass | 当前被调用的对象的class | #root.targetClass |
args | 当前方法参数组成的数组 | #root.args[0] |
caches | 当前被调用的方法使用的Cache | #root.caches[0].name |