从同一类中调用时忽略 Spring 缓存 @Cacheable 方法 [英] Spring cache @Cacheable method ignored when called from within the same class

查看:40
本文介绍了从同一类中调用时忽略 Spring 缓存 @Cacheable 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从同一个类中调用 @Cacheable 方法:

I'm trying to call a @Cacheable method from within the same class:

@Cacheable(value = "defaultCache", key = "#id")
public Person findPerson(int id) {
   return getSession().getPerson(id);
} 

public List<Person> findPersons(int[] ids) {
   List<Person> list = new ArrayList<Person>();
   for (int id : ids) {
      list.add(findPerson(id));
   }
   return list;
}

并希望 findPersons 的结果也被缓存,但是 @Cacheable 注释被忽略,并且 findPerson 方法每次都被执行.

and hoping that the results from findPersons are cached as well, but the @Cacheable annotation is ignored, and findPerson method got executed everytime.

是我做错了什么,还是有意为之?

Am I doing something wrong here, or this is intended?

推荐答案

这是因为在 Spring 中创建代理以处理缓存、与事务相关的功能的方式.这是 Spring 如何处理它的一个很好的参考 - 事务、缓存和 AOP:了解 Spring 中的代理使用

This is because of the way proxies are created for handling caching, transaction related functionality in Spring. This is a very good reference of how Spring handles it - Transactions, Caching and AOP: understanding proxy usage in Spring

简而言之,自我调用绕过了动态代理,并且作为动态代理逻辑一部分的任何横切关注点,如缓存、事务等也被绕过.

In short, a self call bypasses the dynamic proxy and any cross cutting concern like caching, transaction etc which is part of the dynamic proxies logic is also bypassed.

修复方法是使用 AspectJ 编译时或加载时编织.

The fix is to use AspectJ compile time or load time weaving.

这篇关于从同一类中调用时忽略 Spring 缓存 @Cacheable 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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