Improve @Cacheable documentation regarding java.util.Optional

This commit improves the documentation for @Cacheable to point out that
`null` will be stored in the cache for an empty `Optional` return value.

Closes gh-27184
This commit is contained in:
Sam Brannen
2021-07-27 15:05:43 +02:00
parent 42edef0bcc
commit 161c9dc3bd
2 changed files with 14 additions and 10 deletions

View File

@@ -5688,7 +5688,7 @@ method -- if at least one cache is hit, the associated value is returned.
NOTE: All the other caches that do not contain the value are also updated, even though
the cached method was not actually invoked.
The following example uses `@Cacheable` on the `findBook` method:
The following example uses `@Cacheable` on the `findBook` method with multiple caches:
[source,java,indent=0,subs="verbatim,quotes"]
----
@@ -5896,9 +5896,11 @@ want to cache paperback books, as the following example does:
<1> Using the `unless` attribute to block hardbacks.
The cache abstraction supports `java.util.Optional`, using its content as the cached value
only if it is present. `#result` always refers to the business entity and never a
supported wrapper, so the previous example can be rewritten as follows:
The cache abstraction supports `java.util.Optional` return types. If an `Optional` value
is _present_, it will be stored in the associated cache. If an `Optional` value is not
present, `null` will be stored in the associated cache. `#result` always refers to the
business entity and never a supported wrapper, so the previous example can be rewritten
as follows:
[source,java,indent=0,subs="verbatim,quotes"]
----
@@ -5906,8 +5908,8 @@ supported wrapper, so the previous example can be rewritten as follows:
public Optional<Book> findBook(String name)
----
Note that `result` still refers to `Book` and not `Optional`. As it might be `null`, we
should use the safe navigation operator.
Note that `#result` still refers to `Book` and not `Optional<Book>`. Since it might be
`null`, we use SpEL's <<core.adoc#expressions-operator-safe-navigation, safe navigation operator>>.
[[cache-spel-context]]
===== Available Caching SpEL Evaluation Context