Archive

Archive for the ‘Caching’ Category

Caching Java methods with Spring 3

April 27, 2010 7 comments

A while back I wrote about caching Java methods using an earlier version of Spring, but now I am pleased to announce that you can cache your methods using annotations with Spring 3 using Ehcache annotations for Spring.

Similar to my other post you can cache a Java method in a Spring bean by simply adding the annotation.

@Cacheable(cacheName=”dogCache”)
public Collection getDogs() throws Exception {

I really put this annotation to work in my latest project because I called many Web Services in my code that return very static data that is managed by our Enterprise Service Bus. There isn’t any need to go get the data every time since it hardly ever changes.

Using the annotation, I specify that the cache region I want to use is dogCache from the ehcache.xml file and I have it configured specific to have it handle caching dogs exactly like I want it to, even to overflow to disk if necessary. Now let’s look at the configuration necessary.

You will need to drip the jar file for ehcache-annotations in your WEB-INF/lib and then make the following modifications to your applicationContext.xml.

classpath:ehcache-spring.xml

And that’s it, you are now caching your results. Be very cautious with using this, each and every method that gets cached must be thoroughly thought through. For example, I accidentally placed this annotation on a method that returned domain objects that were already configured to be cached via Hibernate, thus doubling the amount of memory that the server was using for each object loaded.

While a very powerful tool that can increase performance, caching can also decrease it.

Follow

Get every new post delivered to your Inbox.