Sub topic 6
Caching selectively with condition and unless
This chapter assumes you can already annotate a method with @Cacheable, build a key with SpEL, and run a Spring Boot application with caching enabled. By default @Cacheable stores every result for every call. Often that is wrong. Some calls are not worth caching, and some results should never be stored. The condition and unless attributes let you express both rules.
Two questions at two moments
condition and unless look similar, but they are evaluated at different times and answer different questions.
| Attribute | Evaluated | Question it answers | Can use `#result`? |
|---|---|---|---|
| `condition` | Before the method runs | Should this call use the cache at all? | No |
| `unless` | After the method returns | Should this result be kept out of the cache? | Yes |
Both attributes take a SpEL expression that must evaluate to a boolean. You can use them together on the same annotation.
The diagram shows a behavior that surprises many people. When condition is false, Spring does not even read the cache. If an entry already exists for that key, the call still ignores it and runs the method. When unless is true, the lookup has already happened. A cached entry would have been returned before unless was ever consulted.
Using condition to skip caching for some arguments
Use condition when you can decide from the arguments alone. The example below skips caching for very short search terms. Short terms match many products and rarely repeat, so they would fill the cache with entries that are unlikely to be reused.
@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 "ab" runs the method every time and stores nothing. A call with "key" is cached under the key key.
A common use of condition is an explicit bypass flag. It gives callers a way to force fresh data:
@Cacheable(cacheNames = "products", key = "#id", condition = "!#forceRefresh")
public Product findById(Long id, boolean forceRefresh) {
return store.get(id);
}Note that this bypass reads fresh data but does not update the cache. Add @CachePut semantics if the fresh value should replace the cached one.
You can refer to arguments by name (#name) only when parameter names are available at runtime. Spring Boot's Maven and Gradle plugins compile with -parameters, so this normally works. If you compile without it, use the positional forms #p0, #a0, or #root.args[0].
Using unless to keep results out of the cache
Use unless when the decision depends on what the method returned. The #result variable holds the return value. If the method returns an Optional, #result refers to the unwrapped value, not the Optional.
The most common rule is to never cache null:
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product findById(Long id) {
return store.get(id);
}Without this rule, a lookup for an id that does not exist yet would cache null. When the product is created later, readers would keep seeing null until the entry expires or is evicted.
Another common rule is to skip empty collections:
@Cacheable(cacheNames = "productSearch", key = "#name.toLowerCase()", unless = "#result.isEmpty()")If the method can return null, guard the expression, as in #result != null and #result.isEmpty(). Otherwise SpEL throws an exception when it evaluates the expression.
unless and null values in the provider
Providers differ in how they treat null. The ConcurrentMapCacheManager that Boot uses by default, and Caffeine, accept null values. Redis does too, unless you set spring.cache.redis.cache-null-values=false. With that setting, a method that returns null and has no unless guard fails with an IllegalArgumentException saying the cache does not allow null values. The unless = "#result == null" guard keeps the code correct whichever provider you choose.
Combining both attributes
The two attributes work well together. This example skips caching for tiny search terms before the call, and skips empty results after it:
@Cacheable(
cacheNames = "productSearch",
key = "#name.toLowerCase()",
condition = "#name.length() > 2",
unless = "#result.isEmpty()")
public List<Product> searchByName(String name) {
return store.values().stream()
.filter(p -> p.name().toLowerCase().contains(name.toLowerCase()))
.toList();
}For a call to be cached, condition must be true and unless must be false.
What you can use inside the expressions
Besides method arguments, SpEL in these attributes has access to a small set of variables.
#root.method,#root.methodName,#root.target, and#root.targetClassdescribe the invoked method and the object behind the proxy.#root.argsis the argument array.#p0and#a0are shorthand for the first argument.#root.cachesis the collection of caches involved in the operation.#resultis available only inunless, and inconditionorunlesson operations that run after the method.
Using #result in the condition of @Cacheable fails, because the method has not run yet. Spring reports this as an evaluation error at call time, not at startup. A test is the reliable way to catch it.
condition on @CachePut and @CacheEvict
@CachePut and @CacheEvict also accept condition. For example, you can refresh the cache only for active products, or evict only when an argument has a certain value. @CacheEvict additionally has beforeInvocation. With the default false, eviction happens after the method succeeds. Setting it to true evicts before the call, even if the method then throws. The next chapter's topic, keeping the cache consistent, builds on these options.
@CachePut has unless as well, and it works the same way as on @Cacheable. It lets you skip updating the cache for results you do not want stored.
Verifying the behavior with a test
Selective caching is easy to get subtly wrong, so test it. The service below counts how many times the method body really executes. It uses the Product record from earlier chapters.
package com.example.shop;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class SearchService {
private final Map<Long, Product> store = new ConcurrentHashMap<>();
private final AtomicInteger executions = new AtomicInteger();
public void save(Product product) {
store.put(product.id(), product);
}
public int executions() {
return executions.get();
}
@Cacheable(
cacheNames = "productSearch",
key = "#name.toLowerCase()",
condition = "#name.length() > 2",
unless = "#result.isEmpty()")
public List<Product> searchByName(String name) {
executions.incrementAndGet();
return store.values().stream()
.filter(p -> p.name().toLowerCase().contains(name.toLowerCase()))
.toList();
}
}The test checks each rule by comparing the execution counter before and after repeated calls:
package com.example.shop;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
@SpringBootTest
class SelectiveCachingTest {
@Autowired
SearchService service;
@Autowired
CacheManager cacheManager;
@BeforeEach
void setUp() {
service.save(new Product(1L, "Keyboard", new BigDecimal("49.90")));
cacheManager.getCache("productSearch").clear();
}
@Test
void shortTermsBypassTheCache() {
int before = service.executions();
service.searchByName("ke");
service.searchByName("ke");
assertThat(service.executions() - before).isEqualTo(2);
}
@Test
void emptyResultsAreNotStored() {
int before = service.executions();
service.searchByName("zzz");
service.searchByName("zzz");
assertThat(service.executions() - before).isEqualTo(2);
}
@Test
void normalResultsAreCached() {
int before = service.executions();
service.searchByName("KEY");
service.searchByName("key");
assertThat(service.executions() - before).isEqualTo(1);
}
}The last test also confirms the key expression. "KEY" and "key" normalize to the same key, so the second call is a hit.
Common mistakes
- Using
#resultincondition. It is not available yet. Useunless. - Inverting the logic of
unless. The expression says when to skip storing, not when to store.unless = "#result != null"caches onlynull. - Expecting
condition = falseto evict. It only bypasses the cache. Existing entries stay and can become stale. Use@CacheEvictto remove them. - Dereferencing a possibly null
#result.#result.isEmpty()throws when the method returnsnull. Guard it with#result != null and .... - Writing the expression in the wrong language. SpEL uses
and,or, and!, and also accepts&&and||. String literals use single quotes inside the Java string, as in#type == 'book'.
Exercise
A method Product findById(Long id) is annotated @Cacheable(cacheNames = "products", key = "#id", condition = "#result != null"). What happens when it is called, and how do you fix it?
Show answer
Spring evaluates condition before the method runs, when no #result exists, so the call fails with a SpEL evaluation error instead of caching selectively. Move the check to unless: @Cacheable(cacheNames = "products", key = "#id", unless = "#result == null"). That stores every non-null result and keeps null out of the cache.
Exercise
A @Cacheable method has condition = "#name.length() > 2". The cache already holds an entry under the key ab, left over from an older version of the code. A caller invokes searchByName("ab"). Does it get the cached entry?
Show answer
No. The condition is false, so Spring skips the cache lookup as well as the store, and the method body runs. The old entry stays in the cache unused until it expires or is evicted.