@Caching With Multiple Keys
You can use Spring SimpleKey class
@Cacheable(value = "barCache", key = "new org.springframework.cache.interceptor.SimpleKey(#bar.id, #bar.name)")
You can use this approach also
@Override
@Cacheable(key="{#bar.name, #bar.id}")
public int foo(Bar bar) {
....
}
It is suggested not to use hashcode as keys @Cacheable key on multiple method arguments
Both answers by @Biju and @vsingh are correct; but I would like to add one more alternative if the Bar
object you are trying to cache is complex or the foo
method contains a large amount of parameters using SpEL might not be the most ideal solution for generating the key.
Alternatively you may want to consider keyGenerator
.
Example:
@Override
@Cacheable(value="barCahceKey", keyGenerator="barKeyGenerator")
public int foo(Bar bar) {
....
}
@Component
public class BarKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object o, Method method, Object... objects) {
// TODO logic to generate unique key
return "Bar_Key_Generator_With_Params_etc";
}
}
With this approach you have the fully flexibility of how the key is constructed.
KeyGenerator API
Yes, you can specify using a Spring-EL expression along these lines:
@Override
@Cacheable(key="#bar.name.concat('-').concat(#bar.id)")
public int foo(Bar bar) {
....
}
or define a modified hashCode on bar and call that:
@Override
@Cacheable(key="#bar.hashCodeWithIdName")
public int foo(Bar bar) {
....
}