I\'m trying to implement Spring 3.1 caching as explained here and here, but it doesn\'t seem to be working: my method is run through every time even though it is marked @cacheab
In addition to Lee Chee Kiam: Here is my solution for small projects with only marginal usage of bypassing (not annotated) method calls. The DAO is simply injected into itself as a proxy and calls it's own methods using that proxy instead of a simple method call. So @Cacheable is considered without doing complicated insturmentation.
In-code documentation is strongly advidsed, as it may look strange 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 also advice the AspectJ solution as Lee Chee Kiam did.
@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;
}
}
From http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with @Cacheable - considering using the aspectj mode in this case.
and
Method visibility and
@Cacheable
/@CachePut
/@CacheEvict
When using proxies, you should apply the
@Cache
annotations only to methods with public visibility.
someMethod
in the same target object. @Cacheable
method is not public.You need to define a cache that matches the name you are referencing in you annotation ("testmethod"). Create an entry in your ehcache.xml for that cache as well.