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

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

问题描述

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

@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方法.

我在这里做错什么了吗?还是故意的?

解决方案

这是因为在Spring中创建了用于处理缓存和事务相关功能的代理的方式.这是Spring如何处理它的很好参考-

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?

解决方案

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.

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

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

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