Spring Cache @Cacheable - 从同一个 bean 的另一个方法调用时不起作用 [英] Spring Cache @Cacheable - not working while calling from another method of the same bean

查看:39
本文介绍了Spring Cache @Cacheable - 从同一个 bean 的另一个方法调用时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从同一个 bean 的另一个方法调用缓存方法时,Spring 缓存不起作用.

这是一个例子,可以清楚地解释我的问题.

Here is an example to explain my problem in clear way.

配置:

<cache:annotation-driven cache-manager="myCacheManager" />

<bean id="myCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="myCache" />
</bean>

<!-- Ehcache library setup -->
<bean id="myCache"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true">
    <property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>

<cache name="employeeData" maxElementsInMemory="100"/>  

缓存服务:

@Named("aService")
public class AService {

    @Cacheable("employeeData")
    public List<EmployeeData> getEmployeeData(Date date){
    ..println("Cache is not being used");
    ...
    }

    public List<EmployeeEnrichedData> getEmployeeEnrichedData(Date date){
        List<EmployeeData> employeeData = getEmployeeData(date);
        ...
    }

}

结果:

aService.getEmployeeData(someDate);
output: Cache is not being used
aService.getEmployeeData(someDate); 
output: 
aService.getEmployeeEnrichedData(someDate); 
output: Cache is not being used

getEmployeeData 方法调用在第二次调用中按预期使用缓存 employeeData.但是当 getEmployeeData 方法在 AService 类中(在 getEmployeeEnrichedData 中)被调用时,缓存没有被使用.

The getEmployeeData method call uses cache employeeData in the second call as expected. But when the getEmployeeData method is called within the AService class (in getEmployeeEnrichedData), Cache is not being used.

这是 spring 缓存的工作方式还是我遗漏了什么?

推荐答案

我相信这就是它的工作方式.从我记得读过的内容来看,生成了一个代理类,它拦截所有请求并使用缓存值进行响应,但同一类中的内部"调用不会获得缓存值.

I believe this is how it works. From what I remember reading, there is a proxy class generated that intercepts all requests and responds with the cached value, but 'internal' calls within the same class will not get the cached value.

来自 https://code.google.com/p/ehcache-spring-annotations/wiki/UsingCacheable

只有通过代理传入的外部方法调用拦截.这意味着自调用实际上是一个方法在目标对象中调用目标对象的另一个方法,不会在运行时导致实际的缓存拦截,即使被调用的方法用@Cacheable 标记.

Only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual cache interception at runtime even if the invoked method is marked with @Cacheable.

这篇关于Spring Cache @Cacheable - 从同一个 bean 的另一个方法调用时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆