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<>();

    public Object get(String key) {
        return cache.containsKey(key) ? cache.get(key) : null;

    public void put(String key, Object value) {
        cache.put(key, value);
For use in any class, just inject this bean and use the put() and get() methods to store and retrieve values.
private RequestDataCache requestDataCache;