Learnitweb

Customizing the ConcurrentMapCacheManager

1. Introduction

By default, Spring Boot provides a simple in-memory cache via ConcurrentMapCacheManager.
This is ideal for testing, prototyping, or small-scale applications where we don’t want to set up an external cache provider.

However, we can customize its behavior to control things like:

  • Whether null values are stored
  • Whether cached values should be stored as deep copies (serialization)
  • Pre-configured cache names

2. Project Setup

We’ll customize caching by creating a configuration class in the config package.

package com.example.library.config;

import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CacheConfig implements CacheManagerCustomizer<ConcurrentMapCacheManager> {

    @Override
    public void customize(ConcurrentMapCacheManager cacheManager) {
        // Example customizations
        cacheManager.setAllowNullValues(false);  // Don't store null values
        cacheManager.setStoreByValue(true);      // Store deep copies (requires Serializable)
        cacheManager.setCacheNames(java.util.List.of("books")); // Predefine cache names

        System.out.println("✅ CacheManager customization applied");
    }
}

3. Understanding the Customization Options

3.1 setAllowNullValues(boolean)

  • Default: true (null values can be stored)
  • Setting to false prevents caching of null results.
  • Helps avoid caching “no result” queries, which may become valid later.
cacheManager.setAllowNullValues(false);

3.2 setStoreByValue(boolean)

  • Default: false (store by reference)
  • If true, values are serialized before storage, meaning:
    • The original object and the cached copy are independent.
    • All cached objects must implement Serializable.
cacheManager.setStoreByValue(true);

When enabling this, ensure your cached entities (e.g., Book) implement Serializable:

public class Book implements Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String title;
    // getters/setters
}

3.3 setCacheNames(Collection)

  • Predefines the list of caches managed by this cache manager.
  • Useful if you want strict control over cache creation.
cacheManager.setCacheNames(List.of("books", "authors"));