Sub topic 6
Caching selectively with condition and unless
This chapter assumes you can write a Spring Boot service, use @Cacheable, and read simple SpEL (Spring Expression Language) expressions such as #id. Not every result deserves a cache entry. Two attributes on @Cacheable let you decide: condition and unless.
Two attributes, two moments
The attributes differ in when Spring evaluates them.
conditionis checked before the method runs. If it is false, Spring skips the cache completely. It does not look up an entry and it does not store one. The method always runs.unlessis checked after the method runs. If it is true, Spring does not store the result. The lookup before the call still happens, so a cache hit can still be returned.
Because condition runs first, it can only use the method arguments (and things like #root). Because unless runs later, it can also use #result.
Using condition
The search example from the plan skips caching for very short terms. Short terms such as "a" match many products and are rarely repeated, so they would fill the cache with little benefit.
@Cacheable(
cacheNames = "productSearch",
key = "#name.toLowerCase()",
condition = "#name.length() > 2")
public List<Product> searchByName(String name) {
return store.values().stream()
.filter(p -> p.name().toLowerCase().contains(name.toLowerCase()))
.toList();
}A call with "ke" runs the method every time. A call with "key" is cached under the key key.
Using unless
The findById method from the earlier chapter used unless to avoid caching a missing product.
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product findById(Long id) {
return store.get(id);
}If store.get(id) returns null, nothing is stored. A product added later is then found on the next call, instead of the cache hiding it behind a stored null.
You can use any property of the result. This variant skips cheap products:
@Cacheable(
cacheNames = "products",
key = "#id",
unless = "#result == null or #result.price().compareTo(new java.math.BigDecimal('10')) < 0")
public Product findById(Long id) {
return store.get(id);
}Note the #result == null or ... order. SpEL evaluates left to right and stops early, so the null check protects the call to price().
Combining both
You can use both on one annotation. Spring caches only when condition is true and unless is false.
@Cacheable(
cacheNames = "productSearch",
key = "#name.toLowerCase()",
condition = "#name.length() > 2",
unless = "#result.isEmpty()")
public List<Product> searchByName(String name) { ... }Common mistakes
- Using
#resultincondition. The result does not exist yet, so the expression fails. Useunlessfor anything that depends on the result. - Reading
conditionas "cache when true" andunlessas "cache when true". They are opposites:condition = trueallows caching,unless = trueprevents it. - Forgetting that
unlessstill allows cache hits. If an entry already exists, it is returned even if the stored value would now failunless. - Writing a SpEL expression that throws, such as calling a method on a null argument. The call then fails with an exception instead of skipping the cache.
Exercise
A method is annotated with @Cacheable(cacheNames = "users", condition = "#id > 0", unless = "#result == null"). What happens for findUser(-5L), and what happens for findUser(7L) when no user 7 exists?
Show answer
For -5L, condition is false, so Spring skips the cache entirely and runs the method every time, with no lookup and no storage. For 7L, condition is true, so Spring looks up the cache, misses, and runs the method. The result is null, so unless is true and nothing is stored. The next call for 7 runs the method again.