61

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;
}

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?

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
David Zhao
  • 4,284
  • 11
  • 46
  • 60
  • Similar question: http://stackoverflow.com/questions/16899604/spring-cache-cacheable-not-working-while-calling-from-another-method-of-the-s#35438619. Here is another simple and good solution: http://stackoverflow.com/questions/16899604/spring-cache-cacheable-not-working-while-calling-from-another-method-of-the-s#35438619 – Grigory Kislin Feb 16 '16 at 17:06

3 Answers3

61

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.

uthark
  • 5,333
  • 2
  • 43
  • 59
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • We had the same problem with transactional annotations and did exactly as Biju posted. No problems since then. – Gonzalo Aug 24 '12 at 20:37
  • 1
    @Gonzalo Just read the blog, could you elaborate on using AspectJ at compile time to solve this? thx! – David Zhao Aug 24 '12 at 22:38
  • 1
    I have one example of using caching annotations with compile time aspectj weaving at - https://github.com/bijukunjummen/cache-sample.git , the behavior is similar to yours, a method self calling an @Cacheable method – Biju Kunjummen Aug 24 '12 at 23:49
  • Also, one bad fix will be to get the proxy and make the call through that - `((PersonService)AopContext.currentProxy())).findPerson(id)` – Biju Kunjummen Aug 27 '12 at 11:30
  • @David We only had to include this in our applicationContext.xml: which worked with the same Transactional annotations. Didn't try with Cacheable methods though – Gonzalo Aug 27 '12 at 12:17
  • @Gonzalo I do have in the context configuration xml, but still calling findPerson(id) from findPersons(ids) won't trigger the caching event – David Zhao Aug 27 '12 at 18:14
  • No David, even `proxy-target-class=true` will not work, it just forces creation of CGLIB based proxies, where the target class is subclassed but still wraps around the proxied object - so `this` in the proxied object will still resolve to the proxied object and bypass the proxy. The only fix is aspectj or calling via the proxy through `((PersonService)AopContext.currentProxy())).findPerson(id)` – Biju Kunjummen Aug 27 '12 at 18:30
  • I injected an instance of the service from the applicationContext in a post-construct method, and called that rather than "this" and that worked- – chrismarx May 15 '15 at 19:53
  • Internal cache configuration could be used to "proxify" the method calls, see example in this answer: https://stackoverflow.com/a/48168762/907576 – radistao Jan 09 '18 at 13:02
30

Here is what I do for small projects with only marginal usage of method calls within the same class. In-code documentation is strongly advidsed, as it may look strage to colleagues. But its easy to test, simple, quick to achieve and spares me the full blown AspectJ instrumentation. However, for more heavy usage I'd advice the AspectJ solution.

@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
class PersonDao {

    private final PersonDao _personDao;

    @Autowired
    public PersonDao(PersonDao personDao) {
        _personDao = personDao;
    }

    @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(_personDao.findPerson(id));
        }
        return list;
    }
}
Mario Eis
  • 2,724
  • 31
  • 32
  • Could you please explain why it works after add @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)? What is used for? – jeffery.yuan Jan 19 '17 at 03:24
  • 5
    Because to inject PersonDao into PersonDao you need to have an instance of PersonDao before it gets instantiated :) To get around that, a stub proxy ([see doc](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-scoped-proxy)) is created, injected and later filled with the same PersonDao instance it got injected to. Sooo, PersonDao can hold an instance of itself, wrapped into a stub proxy. [Easy as that :)](http://memeguy.com/photos/images/playing-portal-co-op-this-is-the-main-argument-with-my-roommate-40939.jpg) Don't know if that was clear enough... :D – Mario Eis Jan 19 '17 at 12:39
  • Thanks, it still works great! Note that I had to replace all lines before `@Cacheable... find Person()` by `@Autowired private PersonDao _personDao;` – nkatsar Feb 15 '19 at 14:38
  • The approach does not work if the class autowires some third class. In that case, the third class instances are not populated (remain null) in the _personDao instance. – JRA_TLL Jul 14 '23 at 14:53
  • Note that findPerson must be public! If it was private, all its field were null. – JRA_TLL Jul 14 '23 at 15:31
2

For anyone using the Grails Spring Cache plugin, a workaround is described in the documentation. I had this issue on a grails app, but unfortunately the accepted answer seems to be unusable for Grails. The solution is ugly, IMHO, but it works.

The example code demonstrates it well:

class ExampleService {
    def grailsApplication

    def nonCachedMethod() {
        grailsApplication.mainContext.exampleService.cachedMethod()
    }

    @Cacheable('cachedMethodCache')
    def cachedMethod() {
        // do some expensive stuff
    }
}

Simply replace exampleService.cachedMethod() with your own service and method.

Dónal Boyle
  • 3,049
  • 2
  • 25
  • 40