Spring cache @Cacheable method ignored when called from within the same class
Solution 1
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.
Solution 2
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;
}
}
Solution 3
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.
David Zhao
Updated on July 26, 2022Comments
-
David Zhao almost 2 years
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, andfindPerson
method got executed everytime.Am I doing something wrong here, or this is intended?
-
Gonzalo over 11 yearsWe had the same problem with transactional annotations and did exactly as Biju posted. No problems since then.
-
David Zhao over 11 years@Gonzalo Just read the blog, could you elaborate on using AspectJ at compile time to solve this? thx!
-
Biju Kunjummen over 11 yearsI 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
-
Biju Kunjummen over 11 yearsAlso, one bad fix will be to get the proxy and make the call through that -
((PersonService)AopContext.currentProxy())).findPerson(id)
-
Gonzalo over 11 years@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
-
David Zhao over 11 years@Gonzalo I do have <aop:aspectj-autoproxy proxy-target-class="true" /> in the context configuration xml, but still calling findPerson(id) from findPersons(ids) won't trigger the caching event
-
Biju Kunjummen over 11 yearsNo 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 - sothis
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)
-
chrismarx about 9 yearsI injected an instance of the service from the applicationContext in a post-construct method, and called that rather than "this" and that worked-
-
jeffery.yuan over 7 yearsCould you please explain why it works after add @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)? What is used for?
-
Mario Eis over 7 yearsBecause 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
-
radistao over 6 yearsInternal cache configuration could be used to "proxify" the method calls, see example in this answer: stackoverflow.com/a/48168762/907576
-
nkatsar over 5 yearsThanks, it still works great! Note that I had to replace all lines before
@Cacheable... find Person()
by@Autowired private PersonDao _personDao;