【发布时间】:2018-10-05 21:27:08
【问题描述】:
我通过添加@Cachable 注释为公共方法启用缓存,如下所示:
@Cacheable(cacheNames = "saas_setting", //
key = "#key")
public Setting get(String key) { ... }
另一方面,我添加了 cacheManager bean:
<bean id="cacheManager"
class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
name="saas_setting" />
</set>
</property>
</bean>
我启用 AOP:
<aop:aspectj-autoproxy
proxy-target-class="true"/>
然后启用缓存:
<cache:annotation-driven
mode="aspectj"
proxy-target-class="true"/>
但是,结果不会被缓存,并且当从系统的其他部分调用该方法时会调用该方法。
我在方法中放了一个刹车点,检查调用堆栈:堆栈中没有CachInterceptor?!
编辑:
这是完整的配置文件:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.3.xsd">
<!-- Enable AspectJ style of Spring AOP -->
<aop:aspectj-autoproxy
proxy-target-class="true"/>
<!-- Enable cache -->
<cache:annotation-driven
mode="aspectj"
proxy-target-class="true"/>
<bean id="cacheManager"
class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
name="saas_setting" />
</set>
</property>
</bean>
<bean name="applicationProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<value>resources/server.properties</value>
<value>resources/modules/*.properties</value>
<value>resources/jetty/*.properties</value>
<value>resources/db/#{systemProperties['db.dialect']}.properties
</value>
<value>resources/db/#{systemProperties['db.orm']}.properties</value>
</list>
</property>
</bean>
<import resource="../context/beans-*.xml" />
</beans>
编辑:
基于 Spring 文档:
处理缓存注释的默认建议模式是“代理”,它只允许通过代理拦截调用;同一类中的本地调用不能以这种方式被拦截。对于更高级的拦截模式,请考虑切换到“aspectj”模式并结合编译时或加载时编织。
在我的代码的某些部分,私有方法将被缓存。所以我必须将 AspectJ 与加载时编织一起使用。
【问题讨论】:
-
请添加完整的xml配置