25.4. Adding Caching to Application Code
To add entries to the cache add the @Cacheable
annotation to select methods. This annotation will add any returned values to the indicated cache. For instance, consider a method that returns a Book
based on a particular key. By annotating this method with @Cacheable
:
@Cacheable(value = "books", key = "#bookId") public Book findBook(Integer bookId) {...}
Book
instances returned from findBook(Integer bookId)
will be placed in a named cache books
, using the bookId
as the value's key.
Important
To remove entries from the cache annotate the desired methods with @CacheEvict
. This annotation can be configured to evict all entries in a cache, or to only affect entries with the indicated key. Consider the following examples:
// Evict all entries in the "books" cache @CacheEvict (value="books", key = "#bookId", allEntries = true) public void deleteBookAllEntries() {...} // Evict any entries in the "books" cache that match the passed in bookId @CacheEvict (value="books", key = "#bookId") public void deleteBook(Integer bookId) {...]}