spring cache 提供了基于注解的緩存配置方法,其實現原理和事務管理的實現是一樣的, 都是通過 spring aop來實現的。spring aop 有一個問題, 默認 aop的實現是使用java 動態(tài)代理技術來實現的, 這樣就會導致,同一個對象內的方法之間的調用,是不會被aop攔截到的。
要解決這個問題,我們可以選擇調整代碼的位置外,讓緩存的方法和調用它的方法分離在不同的類中,但是這種解決方案是不完美的,會導致原本內聚的類,分散在了不同的地方。
除了調整代碼外,還有什么辦法能支持這種情況?
使用AspectJ 進行 織入。
AspectJ 織入器weaver 支持三種織入方式:
- compile-time weaving 使用aspectj 編譯器進行編譯源碼
- post-compile weaving 對class 文件進行織入
- load-time weaving(LTW) 當class loader 加載類的時候,進行織入
使用
通過JVM的-javaagent 加載代理,在代理內持有Instrumentation 對象,方便后續(xù)的注冊class translate hook。
-javaagent:D:\lib\spring-instrument\spring-instrument-4.3.0.RELEASE.jar
spring cache 配置 mode="aspectj"
<?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:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:load-time-weaver/>
<cache:annotation-driven mode="aspectj"/>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg ref="redisTemplate"/>
</bean>
<bean id="propertyConfigurer3" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="3" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="minIdle" value="${redis.minIdle}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.password}" />
<property name="usePool" value="true" />
<property name="poolConfig" ref="poolConfig" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</beans>
META-INF/aop.xml 聲明需要進行織入的目標類
<aspectj>
<weaver options="-verbose -showWeaveInfo">
<include within="com.xxx..*"/>
</weaver>
</aspectj>