Skip to main content


Showing posts from 2015

Spring MVC Request Level Cache

Today we will look at a very simple way to create a cache that can store different values for same key, for different HTTP requests. Recently I was working on RESTFul web services using Spring MVC. I was faced with a situation where I was querying the database multiple times for same data. I thought it would be good if I could cache this data and avoid DB calls. Since the data had to be different for each request, I started hunting for a method to create request level cache.  One way is to use ThreadLocal object for storing the cache map, since ThreadLocal stores separate object for each thread, we will have a separate cache map for each request. However, Spring provides an even simpler way to achieve this, by using Request scoped bean. Below is the code for the cache class. @Component @Scope (proxyMode = ScopedProxyMode. TARGET_CLASS , value = "request" ) public class RequestDataCache { private final Map<String, Object> cache = new HashMap<>();