68

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?

1

4 Answers 4

65

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.

Sign up to request clarification or add additional context in comments.

9 Comments

We had the same problem with transactional annotations and did exactly as Biju posted. No problems since then.
@Gonzalo Just read the blog, could you elaborate on using AspectJ at compile time to solve this? thx!
I have one example of using caching annotations with compile time aspectj weaving at - github.com/bijukunjummen/cache-sample.git , the behavior is similar to yours, a method self calling an @Cacheable method
Also, one bad fix will be to get the proxy and make the call through that - ((PersonService)AopContext.currentProxy())).findPerson(id)
@David We only had to include this in our applicationContext.xml: <aop:aspectj-autoproxy proxy-target-class="true" /> which worked with the same Transactional annotations. Didn't try with Cacheable methods though
|
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;
    }
}

5 Comments

Could you please explain why it works after add @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)? What is used for?
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) 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 :) Don't know if that was clear enough... :D
Thanks, it still works great! Note that I had to replace all lines before @Cacheable... find Person() by @Autowired private PersonDao _personDao;
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.
Note that findPerson must be public! If it was private, all its field were null.
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.

Comments

0

If you're accessing cache from withing the same class, you probably don't need spring cache at all.

Take a look at different map implementations:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
    new CacheLoader<Key, Graph>() {
      public Graph load(Key key) throws AnyException {
        return createExpensiveGraph(key);
      }
    });

Java time-based map/cache with expiring keys

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.