Quick revision
The short answer
find() gets @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null"), so a hit skips the method and null results are never stored. update() gets @CachePut(cacheNames = "products", key = "#p.id"), so the method always runs and its return value replaces the entry. delete() gets @CacheEvict(cacheNames = "products", key = "#id"), which removes the entry after the method returns successfully, or before it runs if we set beforeInvocation = true.
What to remember
In this answer, we wrote the three annotations for a ProductService. find() uses @Cacheable with key = "#id" and unless = "#result == null", so a hit skips the method and nulls are not stored. update() uses @CachePut with key = "#p.id", so the method always runs and its return value replaces the entry under the same key. delete() uses @CacheEvict with key = "#id", which removes the entry after a successful call unless beforeInvocation = true. We also saw that condition runs before the call and unless after it, and that Optional results are unwrapped, so an empty Optional counts as null.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
find() gets @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null"), so a hit skips the method and null results are never stored. update() gets @CachePut(cacheNames = "products", key = "#p.id"), so the method always runs and its return value replaces the entry. delete() gets @CacheEvict(cacheNames = "products", key = "#id"), which removes the entry after the method returns successfully, or before it runs if we set beforeInvocation = true.
Why this question is asked
Read, update and delete are the three things almost every service does with an entity, and each needs a different caching annotation. Getting them right keeps the cache in step with the database; getting one wrong leaves stale entries that no TTL is short enough to hide. Interviewers like this coding question because writing three annotations takes a minute, but explaining what each does at runtime shows whether we understand the proxy, the key and the timing. In this answer, we will recap the three annotations, write the service, explain each method's behaviour at runtime with the keys made explicit, and look at two details that often surprise people: Optional return values and allEntries.
1A Quick Recap of the Three Annotations
All three annotations work through a proxy, a wrapper object Spring generates around our bean when caching is enabled with @EnableCaching. The proxy's CacheInterceptor reads the annotation and acts before or after calling our method. The key attribute is a SpEL expression (Spring's expression language) where #id means the parameter named id and #p.id means the id property of the parameter p. Parameter names are available because Spring Boot compiles with the -parameters flag; without it we would write #a0 or #p0 for the first argument.
@Cacheable reads first and only runs the method on a miss. @CachePut always runs the method and writes its result. @CacheEvict removes an entry or, with allEntries = true, the whole cache.
2Writing the ProductService
Here is the service with the three annotations. Notice that all three use the same cache name and keys of the same type, the product id as a long, so they address the same entry.
The key expressions matter more than they look. find(long id) would produce the key 42L with the default key generator too, but update(Product p) would not: the default key would be the Product object itself, a different key from 42L, so the put would write a new entry while the old one stayed behind. Writing key = "#p.id" makes update address the same entry as find. Writing the keys explicitly on all three methods makes the shared key visible to the next reader.
3What Each Annotation Does at Runtime
Let us run a sequence of calls and watch the cache.
| Call | Method runs? | Entry under key 42 afterwards |
|---|---|---|
find(42), first time | yes | Product(42, "Lamp") |
find(42), second time | no, hit | Product(42, "Lamp") |
update(Product 42 "Desk lamp") | yes, always | Product(42, "Desk lamp") |
delete(42) | yes | none |
find(42) after delete | yes, miss | none if the row is gone (null not stored) |
For find(), the interceptor computes the key 42 and calls cache.get(42). On a hit it returns the value and our method never runs, which is the whole point. On a miss it runs the method, evaluates unless = "#result == null" after the call, and stores the result only when it is not null. That is why find(999) is not cached: a missing product should be looked up again next time, in case it has been created since.
For update(), there is no lookup at all. The method always runs, and its return value is put under the key 42, replacing whatever was there. This is why update() should return the saved entity: whatever it returns is exactly what later readers will get from the cache.
For delete(), the method runs first and the eviction happens after it returns. If deleteById() throws, the eviction does not happen, which is usually what we want because the row is still there. With beforeInvocation = true, the entry is removed before the method runs, so it is removed even when the method fails.
4Condition, unless and Optional Results
Two attributes control whether caching happens. condition is evaluated before the call and can switch caching off entirely for that call, for example condition = "#id > 0". unless is evaluated after the call and can only prevent the store, which is why it is the one that can refer to #result. Using condition to check #result is a bug, because there is no result yet when it is evaluated.
If find() returned Optional<Product> instead of a nullable Product, Spring would unwrap it: the cache stores the Product itself, and an empty Optional is treated as a null result. So unless = "#result == null" still skips empty results, and on a hit Spring wraps the cached Product back into an Optional for the caller.
5Follow-up questions
When would you use allEntries = true?
When a change can affect many entries and we cannot name their keys, for example after a bulk price import or a category rename that changes every product listing in it. @CacheEvict(cacheNames = "products", allEntries = true) clears the whole cache in one operation instead of evicting key by key. It is a heavy tool: the next requests all miss, so on a busy cache it can cause a burst of database load. On Redis, clearing a cache may need to scan keys, so check how your version's cache writer clears a cache.
Why should @CachePut and @Cacheable not be combined on one method?
Because they want opposite things. @Cacheable says: skip the method if the value is already cached. @CachePut says: always run the method and store the result. Put on the same method, the behaviour depends on how Spring resolves the conflict, and the method may run when we expected a hit or the cache may be updated in surprising ways. The Spring documentation strongly discourages it; reads and writes should be separate methods.
Why does update() return the Product instead of void?
Because @CachePut stores the return value. A void method would put null into the cache, or nothing useful, and later reads would get a wrong answer. Returning the entity that was actually saved, including any fields the database filled in such as a version number, means the cache holds exactly what the database holds.
6Conclusion
In this answer, we wrote the three annotations for a ProductService. find() uses @Cacheable with key = "#id" and unless = "#result == null", so a hit skips the method and nulls are not stored. update() uses @CachePut with key = "#p.id", so the method always runs and its return value replaces the entry under the same key. delete() uses @CacheEvict with key = "#id", which removes the entry after a successful call unless beforeInvocation = true. We also saw that condition runs before the call and unless after it, and that Optional results are unwrapped, so an empty Optional counts as null.
Open with
For find I would write @Cacheable with cacheNames products, key #id and unless #result == null. At runtime the proxy computes the key, looks in the cache, and on a hit returns the value without running the method.
Then, if they want more
On a miss it runs the method, then evaluates unless, and only stores a non-null result, so a missing product is looked up again next time. For update I would use @CachePut with the same cache and key #p.id.
That matters because the default key would be the Product object itself, which is a different key from the id, so the put would not replace the entry that find reads. CachePut never skips the method: it always runs, and the return value is stored, which is why update returns the saved entity.
For delete I would use @CacheEvict with key #id. By default the eviction happens after the method returns successfully, so if the delete throws the entry stays; with beforeInvocation = true it is removed first, even on failure.
The distinction between condition and unless is timing: condition runs before the call and can disable caching completely, unless runs after and can only veto the store, so only unless can use #result. And if the method returns Optional, Spring caches the content, and an empty Optional counts as null for unless.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Cache abstraction
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write the annotations for a ProductService with three methods: Product find(long id)...": https://scrivio-interview-library.netlify.app/databases/caching/48ff7083fd/