當從同一個bean的另一個方法調用緩存方法時,Spring緩存不工作。Spring Cache @Cacheable - 從同一個bean的另一個方法調用時不工作
下面是一個以清晰的方式解釋我的問題的例子。
配置:
<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
)內被調用時,緩存沒有被使用。
這是彈簧緩存如何工作,或者我錯過了什麼?
「someDate」參數是否使用相同的值? – Dewfy
@Dewfy是的,它是一樣的 – Bala