shrewquest
shrewquest

Reputation: 551

how to specify more than one param in method for spring Cacheable key

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-annotations-cacheable-key The link above shows how to specify a key when all the parameters for a method are not required for the cache key which is the default. But how do you specify more than one param (but not all in the method arg list) as the key for the cache in the Cacheable annotation?

Upvotes: 0

Views: 6673

Answers (2)

user7152981
user7152981

Reputation:

0 param: key is 0

1 param: key is the param

2 or more params: key is hashCode(param0, param1, ...)

Upvotes: 0

John Blum
John Blum

Reputation: 7981

As you know, the key attribute of the @Cacheable annotation allows SpEL to be used. In all cases, the actual key used to access the underlying Cache must "evaluate" to a single value. Therefore, you must employ the power of SpEL to combine the @Cacheable method arguments that form the (unique) key.

By way of example, lets say we want to find a Book by Author, Edition and Title. I.e., we might have a @Cacheable method signature like so...

@Cacheable(cacheNames = "Books", key="#author.name + #edition + #title")
Book findBook(Author author, Integer edition, String title, boolean checkWarehous, boolean includeUsed) {
 ...
}

As you can see, the key is a combination and subset of the method arguments.

Literally any valid SpEL expression used to combine the @Cacheable method arguments for use as a key is applicable.

For complex keys where the individual components (such as Author, Edition, Title etc) of the key are each accessible, then it is best create a custom key class (e.g. BookKey) and use a custom Spring KeyGenerator (e.g. BookKeyGenerator) to generate the Cache key. Note, the method, target class and arguments of the @Cacheable method (e.g. findBook(author, edition, title, ...)) are each made available to your custom KeyGenerator.

Hope this helps.

Upvotes: 6

Related Questions