Why does not the SimpleKeyGenerator consider the method name in Spring Cache Mechanism

938 views Asked by At

We know the implements of SimpleKeyGenerator as below:

@Override
public Object generate(Object target, Method method, Object... params) {
    return generateKey(params);
}

/**
 * Generate a key based on the specified parameters.
 */
public static Object generateKey(Object... params) {
    if (params.length == 0) {
        return SimpleKey.EMPTY;
    }
    if (params.length == 1) {
        Object param = params[0];
        if (param != null && !param.getClass().isArray()) {
            return param;
        }
    }
    return new SimpleKey(params);
}

What is confusing me is that it does not consider the method's name, only considering the parameters. Why??? This leads to two different methods with same parameters have the same key, and then return the same result in cache! What is the purpose of this designing?

1

There are 1 answers

0
wituss On

You can find answer on Spring's GitHub.

The primary reason for this is that the same key needs to be generated for @Cacheable, @CachePut and @CacheEvict annotated method, which will most likely be on different methods and potentially different beans.