Annotations
Five annotations put a cache in front of bean methods: @Cacheable reads and fills it, @CachePut refreshes it, @CacheEvict removes entries, @Caching combines several, and @CacheConfig gives defaults to a class. Keys and conditions are SpEL expressions, as in Spring.
Why
The rules of a cache (which entries, under which key, when to forget them) belong next to the method they speed up, where a reader sees them. Annotations keep the method body free of cache code, and the same annotations work whatever cache stands behind them.
Example
@Service()
@CacheConfig(cacheNames: ['books'])
class Books {
Books(this.api);
final CatalogApi api;
@Cacheable.of(key: '#isbn') // the cache comes from @CacheConfig
Future<Book> find(String isbn, {bool includeReviews = false}) => api.load(isbn);
@Cacheable('books', key: "#isbn + '-' + #lang") // a combined key
Future<Book> translated(String isbn, String lang) => api.translated(isbn, lang);
@Cacheable('books', condition: '#isbn.length() == 13') // cache 13-digit ISBNs only
Future<Book> findIsbn(String isbn) => api.load(isbn);
@Cacheable('books', unless: '#result == null') // do not remember misses
Future<Book?> maybe(String isbn) => api.maybe(isbn);
@CachePut('books', key: '#result.isbn') // Book is @Introspected
Future<Book> save(Book book) => api.save(book);
@CacheEvict('books', allEntries: true) // the catalogue changed
Future<void> reimport() => api.reimport();
@Caching(evict: [CacheEvict('books', key: '#isbn'), CacheEvict('prices', key: '#isbn')])
Future<void> delete(String isbn) => api.delete(isbn);
}
The annotations
| Annotation | What it does |
|---|---|
@Cacheable('books') |
Returns the cached result when there is one; otherwise runs the method and stores the result. |
@CachePut('books', key: '#isbn') |
Always runs the method and stores the result, to refresh the entry. Next to a @Cacheable hit, the method runs anyway only when the put's condition passes (a condition reading #result counts as passing), as in Spring. |
@CacheEvict('books', key: '#isbn') |
Removes the entry after the method returned. allEntries: true clears the whole cache; beforeInvocation: true evicts before the call, so also when it throws. |
@Caching(cacheable: [...], put: [...], evict: [...]) |
Several operations on one method. Repeating an annotation works too. |
@CacheConfig(cacheNames: [...], keyGenerator:, cacheManager:, cacheResolver:) |
On the class: defaults for its methods. |
@Cacheable('books') names one cache. For several caches, or to take them from @CacheConfig, use the .of constructor: @Cacheable.of(cacheNames: ['books', 'isbn']) or @Cacheable.of(key: '#isbn'); the same for CachePut.of and CacheEvict.of. A Dart constructor cannot mix an optional positional name with named parameters.
Options
| Option | On | Meaning |
|---|---|---|
cacheNames |
all | The caches, with .of. |
key |
all | SpEL computing the key. Default: the arguments. |
condition |
all | SpEL; the cache is used only when it is true. |
unless |
@Cacheable, @CachePut |
SpEL with #result; the result is not stored when it is true. It does not prevent a hit. |
sync |
@Cacheable |
For Future methods: concurrent calls with the same key share one call. |
allEntries |
@CacheEvict |
Clears the whole cache. |
beforeInvocation |
@CacheEvict |
Evicts before the call. |
keyGenerator |
all | The name of a KeyGenerator bean (not with key). |
cacheManager |
all | The name of the CacheManager bean to use. |
cacheResolver |
all | The name of a CacheResolver bean that picks the caches (not with cacheManager). |
Where annotations apply
@Cacheable,@CachePut,@CacheEvictand@Cachingon a class apply to every public method that has no cache annotation of its own (not to getters, setters ortoString).- Class-level annotations and
@CacheConfigare read from the class that declares the method's body and, when it has none, from its superclasses (the nearest wins). A base class with@CacheConfigserves the beans that extend it, while a subclass's class-level annotations do not apply to the methods it inherits. @CacheConfigfills in only what an operation leaves open: its cache names when the operation names none, itskeyGeneratorwhen the operation sets neitherkeynorkeyGenerator, itscacheResolver(else itscacheManager) when the operation sets neither.
Keys
Without key, the key is made of the arguments, as Spring's SimpleKeyGenerator does:
| Arguments | Key |
|---|---|
| none | SimpleKey.empty |
| one | the argument itself (a single list, set or map is wrapped in a SimpleKey, since Dart collections compare by identity) |
| several | SimpleKey([...]), which compares by content, collections inside too |
A key that comes out null (from key or a key generator) fails the call with an ArgumentError.
SpEL in key, condition and unless
Written plain, without #{}:
| Expression | Value |
|---|---|
#isbn |
The argument named isbn. |
#p0, #a0 |
The first argument. |
#result |
The result: in unless; in key and condition of @CachePut; in @CacheEvict after the call. |
#root.methodName |
find. |
#root.method.name |
find (also returnType, parameterTypes, parameterNames, parameterCount, as text). |
#root.args |
All arguments; #root.args[1]. |
#root.target |
The bean. |
#root.targetClass |
The bean's class name, Books. |
#root.caches |
The cache names of the operation. |
@region |
The bean named region. |
Reading properties or calling methods of your own objects (#book.isbn, #result.isbn, @clock.zone()) needs @Introspected() on their class: the generator writes the accessors SpEL uses. Strings, numbers, lists and maps work as they are (#isbn.length(), #tags.size()).
Async methods
Methods returning a Future cache the value, not the future: the value is stored when the future completes, a hit returns an already completed Future, and errors are never cached, so the next call tries again.
With sync: true, calls that arrive while the first one is still running wait for it instead of running the method again. A sync operation must be the only cache annotation of the method, use one cache and have no unless. The waiting is shared per cache and key, not per method: two sync methods that use the same cache and compute the same key share one pending result.
A Stream cannot be cached: it can be listened to once. @Cacheable and @CachePut on a method returning a Stream fail the build. Collect the values instead:
@Cacheable('events')
Future<List<Event>> recent() => api.events().toList();
Checked at startup
The annotations of every proxied bean are checked when the bean is created, so a wrong combination fails the startup, naming the member:
keywithkeyGenerator;cacheManagerwithcacheResolver;syncwith other operations, several caches orunless;- an operation without cache names (unless a cache resolver picks them);
@Cacheable/@CachePuton a method returning aStream.
The check is the bean cacheOperationValidator, a startup check in a module of its own, in the build by spring.main.startup-checks.enabled: not set, in debug and profile builds only, so a release build ships none of its code and a wrong annotation fails at the member's first call. true in application.yml or application.properties keeps it in every build, false in none.
In Spring (Java)
@Cacheable(cacheNames = {"books", "isbn"}, key = "#isbn", unless = "#result == null")
public Book find(String isbn) { ... }
The annotations and SpEL variables are Spring's. #root.caches holds cache names, #root.targetClass the class name and #root.method a MethodSignature. The sync rules are checked at startup (Spring checks them at the first call).