Search code examples
springspring-cache

How to create Spring Cache KeyGenerator that allows no caching for specified key


I just want to disable cache for users that are admins. So I write a method to generate keys as below that returns null for admins. But I get

java.lang.IllegalArgumentException: Null key returned for cache operation exeption.

Is there any way achieve that?

//a method that generates a menu for each user
@Cacheable(cacheNames = "topmenu", keyGenerator = "uiComponentKey")
@Override
public String renderResponse() {...}   


//method used by a key generator to generate cache keys.
@Override
public Object getCacheKey() {
    if (user.isAdmin()) {
        return null;
    }
    return user.getUser().getLogin() + "@" + "topmenu";
}

Solution

  • I guess you can achive that using conditional caching feature. Smth like this:

    @Cacheable(cacheNames = "topmenu", condition="#user.isAdmin()")
    @Override
    public String renderResponse(User user) {...}
    

    Note, that you're going to have to pass user object to this method in this case.