Configure Caching Declaration
After configuring your Spring application and enabling caching, the next step is to identify the methods that need to be cached and their respective policies.
You can bind the caching behaviors to the methods using:
- Caching Annotations
- Declarative XML-based Caching
Configure Using Caching Annotations
For caching declarations, the abstraction provides Java annotations that allow methods to trigger cache population or cache eviction.
Example
Let’s consider a web service with two classes that explain how caching takes place using the @Cacheable annotation.
// BookController.java
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
// Get a Spring Service to save objects in the DB. This also caches them with 5min absolute (TTL) expiration.
BookService service = context.getBean(BookService.class);
service.save(new Book(18001, "The Second Machine Age", "Erik Brynjolfsson, Andrew McAfee", new Date(2014, 0, 20)));
// Print all saved books details
printBooks(service.listAll());
// Use Spring Service to get a book from the DB. It actually comes from the cache
Book foundBook = service.findBookByIsbn(18001);
printBookDetails(foundBook);
foundBook.setAuthor("New Author");
Book UpdatedBook = service.update(foundBook);
printBookDetails(UpdatedBook);
context.close();
System.exit(0);
}
// BookService.java
@Service
class BookService {
@Autowired
private BookRepository repo;
public List<Book> listAll() {
return repo.findAll();
}
@CachePut(value = "demoCache", key = "#book.getISBN()")
public Book save(Book book) { return repo.save(book); }
@CachePut(value = "demoCache", key = "#book.getISBN()")
public Book update(Book book) { return repo.save(book); }
@Cacheable(value = "demoCache", key = "#id")
public Book get(int id) {
return repo.findById(id);
}
@Cacheable(value = "demoCache", key = "#isbn")
public Book findBookByIsbn(long isbn) {
return repo.findBookByIsbn(isbn);
}
@CacheEvict(value = "demoCache", allEntries = true)
public void delete(int id) {
repo.deleteById(id);
}
}
To get a detailed understanding and to learn more about other Caching Annotations or the creation of the Custom Key Generator, refer to the Spring Documentation.
Configure using Declarative XML-based Caching
If annotations are not an option, i.e., if you have limited access to the sources or no external code, you can use XML for declarative caching. Here, you can specify the target method and the caching directives externally.
In the configuration below, the bookService is made cacheable. The caching semantics are encapsulated in the cache:advice
definition, which instructs the method getBookNameByIsbn to put data into the cache while the loadBooks method evicts data. Both definitions are working against the demoCache.
Note
When using the class
tag please make sure you use the fully qualified name of your class.
<!-- the service we want to make cacheable -->
<bean id="bookService" class="x.y.service.BookService"/>
<!-- cache definitions -->
<cache:advice id="booksCacheAdvice" cache-manager="cacheManager">
<cache:caching cache="demoCache">
<cache:cacheable method="getBookNameByIsbn" key="#isbn"/>
<cache:cache-evict method="loadBooks" all-entries="true"/>
</cache:caching>
</cache:advice>
Also, for using the Custom Key Generator for cache key generation through XML-based caching, beans created for the key generator need to be defined as shown below in CustomerKeyGenerator
as a class.
<bean id="customerKeyGenerator" class="cachekeygenerator.CustomerKeyGenerator">
Here, the customerKeyGenerator
generates a cache key whenever a customer is added to the customersCache. To use this generator, you must specify the keygenerator
bean in your cache:advice
tag.
<cache:advice id="customerCacheAdvice" key-generator="customerKeyGenerator">
<cache:caching cache="customersCache">
<cache:cacheable method="findCustomerByID"/>
</cache:caching>
</cache:advice>
After modifying all these configurations, your application is now ready to use NCache as a Spring Caching Provider.
See Also
Configure Application for Generic Spring Caching Provider
Configure Application for JCache Caching Provider
NCache as Spring Data Cache