Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:


Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

In this quick tutorial, we’re going to illustrate how to create a custom key generator with Spring Cache.

For an introduction to the above module, please refer to this article.

2. KeyGenerator

This is responsible for generating every key for each data item in the cache, which would be used to lookup the data item on retrieval.

The default implementation here is the SimpleKeyGenerator – which uses the method parameters provided to generate a key. This means that if we have two methods that use the same cache name and set of parameter types, then there's a high probability that it will result in a collision.

It also implies that the cache data can be overwritten by another method.

3. Custom KeyGenerator

A KeyGeneratorneeds to implement just one single method:

Object generate(Object object, Method method, Object... params)

If it isn't implemented or used correctly, it can lead to overwriting cache data.

Let's look at the implementation:

public class CustomKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        return target.getClass().getSimpleName() + "_"
          + method.getName() + "_"
          + StringUtils.arrayToDelimitedString(params, "_");

After that, we have two possible ways of using it; the first is declaring a bean in the ApplicationConfig.

It's important to remark that the class has to extend from CachingConfigurerSupport or implement CacheConfigurer:

public class ApplicationConfig extends CachingConfigurerSupport {
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        Cache booksCache = new ConcurrentMapCache("books");
        return cacheManager;
    public KeyGenerator keyGenerator() {
        return new CustomKeyGenerator();

The second way is using it just for a particular method:

public class BookService {
    @Cacheable(value = "books", keyGenerator = "customKeyGenerator")
    public List<Book> getBooks() {
        List<Book> books = new ArrayList<>();
        books.add(new Book("The Counterfeiters", "André Gide"));
        books.add(new Book("Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
        return books;

4. Conclusion

In this article, we've explored a way of implementing a custom Spring Cache's KeyGenerator.

As always, the full source code of the examples is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:


Generic footer banner
Comments are closed on this article!