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

查看:1033
本文介绍了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 。但是当在 AService 类中调用 getEmployeeData 方法时(在 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天全站免登陆