Cache Abstraction in Spring 3.1.0.M1

Another new feature released yesterday came in parallel with me tryingo ut some annotation based caching strategies. Caching Abstraction basically takes convention from an existing project and makes it part of spring core.

Essentially it introduces a new interface, CacheManager, which can be implemented by a specific cache implementation. From there it adds a few new annotations to make methods cacheable. Here’s an example using my previous posts objects.

Here you’ll notice that the finder method has a @Cachable annotation on it with a name that specifies the cache to store to. it can also use additional attributes, for example a key which uses an expression language to determine a key from the arguments that are passed in. The default is the value of all the method arguments. On the save method I use @CacheEvict to remove the cached element from the cache if it already exists.

This of course won’t work on it’s own, so you’ll have to enable it yourself (which is good… the last thing you need is to discover a production app caching things it shouldn’t be caching). Sadly as of the time of this writing I haven’t discovered how to do this in non-xml, so here is the spring xml file to enable it and use ehcache as the implementation.

The ehcache configuration:

And finally adding this to the AppConfiguration, which includes doing a simple @ImportResource.

When running this example there should be a log message for the first time the method is hit, then it is not seen the second time (since it is being pulled from the cache. This is definitely pretty awesome for implementing Memoization for methods that might just have some CPU intensive computations (but give the exact expected results given a set of of inputs). I’m excited about doing some more work in this area… I’ve done method level caching before (it’s common) but it is awesome to be able to use it without having to DIY. 🙂