Sub topic 2
Controlling Cache Keys in Spring Boot
Assume you know basic Java, Spring beans, dependency injection, and application.properties. This chapter focuses on how annotation-based caching chooses entries and keeps them correct.
Controlling cache keys
A cache key identifies one cached value. Spring can use the method arguments automatically, but explicit keys make the contract clear. SpEL, Spring Expression Language, lets an annotation refer to arguments and results.
@Cacheable(
cacheNames = "productSearch",
key = "#name.trim().toLowerCase()")
public List<Product> searchByName(String name) {
return repository.findByName(name);
}The expressions "Keyboard" and " keyboard " now produce the same key. Choose a key that contains every value that changes the result. If a method depends on both a tenant and an ID, include both:
@Cacheable(
cacheNames = "products",
key = "#tenantId + ':' + #id")
public Product find(String tenantId, Long id) {
return repository.findForTenant(tenantId, id);
}Caching selectively
condition is evaluated before the method runs. It can prevent caching for inputs that should not use the cache. unless is evaluated after the method returns. It can reject a returned value.
@Cacheable(
cacheNames = "productSearch",
key = "#name.toLowerCase()",
condition = "#name.length() > 2",
unless = "#result == null || #result.isEmpty()")
public List<Product> searchByName(String name) {
return repository.findByName(name);
}Here, short names bypass caching. Empty and null results are not stored.
Keeping entries consistent
Use @CachePut when a method writes data and returns the new value. The method always runs, and its result replaces the matching entry. Use @CacheEvict when a value is deleted or when a broader invalidation is safer.
@CachePut(cacheNames = "products", key = "#product.id()")
public Product update(Product product) {
return repository.save(product);
}
@CacheEvict(cacheNames = "products", key = "#id")
public void delete(Long id) {
repository.deleteById(id);
}The read and write annotations must calculate compatible keys.
Proxy behavior and self-invocation
Spring applies caching through a proxy around the bean. A call from another bean passes through that proxy. A method calling another method on the same object does not.
public Product loadForReport(Long id) {
return findById(id); // bypasses the cache proxy
}
@Cacheable(cacheNames = "products", key = "#id")
public Product findById(Long id) {
return repository.findById(id).orElseThrow();
}Move the cached method to another service or call the service through an injected dependency.
Choosing a cache provider
Caffeine is a fast, in-process cache. Each application instance has its own entries. Redis is a shared cache, useful when multiple instances must see the same values.
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10mUse Redis when shared entries matter:
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
spring.cache.redis.cache-null-values=falseChoose expiration and size limits from data freshness and memory requirements, then measure hit and miss rates.
Exercise
Why does a call from one method to another method in the same Spring bean bypass @Cacheable?
Show answer
The call uses this directly instead of passing through Spring's caching proxy, so the cache interceptor does not run.