简体   繁体   中英

Meaning of a key as an argument to the Cacheable annotation

I am trying to use the Spring @Cacheable annotation.

Lets look at:

@Cacheable(value = "employee", key = "#surname")
public Person findEmployeeBySurname(String firstName, String surname, int age) {

    return new Person(firstName, surname, age);

}

Am I right that if I add 2 people with the same surname then only one will be saved in the cache, and the method will return incorrect results sometimes?

When should I specify this argument?

How does spring create the key if I don't specify it explicitly(as I understand I should know it when I use CasheEvict and CashPut annotations)?

JB Nizet is right, it is clearly in the documentation he linked to!

35.3.1 @Cacheable annotation ...

Default Key Generation

Since caches are essentially key-value stores, each invocation of a cached method needs to be translated into a suitable key for cache access. Out of the box, the caching abstraction uses a simple KeyGenerator based on the following algorithm:

 If no params are given, return SimpleKey.EMPTY. If only one param is given, return that instance. If more the one param is given, return a SimpleKey containing all parameters. 

It is the last of the three cases that is importent for your mehtods, wihout cache parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM