While the accepted answer describes how to solve the problem, it fails to answer the actual question which was why Spring behaves like this. So here's the answer for anyone interested.
From the documentation of org.springframework.cache.annotation.EnableCaching
:
Normally, @EnableCaching
will configure Spring's SimpleKeyGenerator
And SimpleKeyGenerator
is defined like so:
public class SimpleKeyGenerator implements KeyGenerator {
@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);
}
}
As you can see, it only looks at the parameters to generate the cache key and completely ignores the method. Which I agree, is total nuts.
But Stéphane Nicoll said:
SimpleKeyGenerator does this on purpose. We had many requests to add more context to the key such as the method signature for instance. We feel this is wrong as the key should be natural and usable outside of how we interact with the cache.