同じ Bean の別のメソッドからキャッシュされたメソッドを呼び出す場合、Spring キャッシュは機能しません。
私の問題を明確に説明するための例を以下に示します。
構成:
<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
予想どおり 2 回目の呼び出しでキャッシュを使用します。ただし、メソッドがクラス内 ( 内)getEmployeeData
で呼び出される場合、キャッシュは使用されません。AService
getEmployeeEnrichedData
これは Spring Cache の動作方法ですか、それとも何か見落としているのでしょうか?
ベストアンサー1
これがその仕組みだと思います。私が読んだ記憶によると、すべてのリクエストをインターセプトしてキャッシュされた値で応答するプロキシ クラスが生成されますが、同じクラス内の「内部」呼び出しではキャッシュされた値は取得されません。
からhttps://code.google.com/p/ehcache-spring-annotations/wiki/UsingCacheable
プロキシ経由で入ってくる外部メソッド呼び出しのみがインターセプトされます。つまり、自己呼び出し、つまりターゲット オブジェクト内のメソッドがターゲット オブジェクトの別のメソッドを呼び出す場合、呼び出されたメソッドが @Cacheable でマークされていても、実行時に実際のキャッシュ インターセプトは行われません。