Spring caching: how @Cacheable works and where it goes wrong
Spring's cache annotations turn a slow method into a map lookup, using a proxy, a key built from the arguments and a pluggable CacheManager. This page explains each part, then runs every annotation and trap with Spring Framework 7.0, from keys that mix up callers to cached objects that every caller shares.
Contents
How the Spring cache abstraction works A first cached method Cache keys, condition and unless Keeping the cache in step with the data: @CachePut and @CacheEvict Traps: self-invocation, shared objects and exceptions Many callers, one miss: sync = true Caching asynchronous results Choosing a cache provider Choosing the right annotation and setting
How the Spring cache abstraction works
A cache keeps the result of an expensive call, such as a database query or a remote request, so that the next call with the same arguments can skip the work. Writing that by hand means the same lines in every method: build a key, look it up in a map, return the value if it is there, otherwise compute it and store it. Spring's cache abstraction moves those lines out of your code and into annotations.
It is built from the same parts as
- A proxy:
makes Spring wrap every bean that has cache annotations. Callers get the proxy, and the proxy decides whether the real method runs at all.@EnableCaching - A key: the proxy turns the method arguments into a cache key. By default one argument is the key itself, and several arguments become a
that holds all of them.SimpleKey - A cache manager: each
has a name, such asCache , and behaves like a map from key to value. The"prices" decides where the data lives: aCacheManager in the same JVM, Caffeine, Redis, or any JCache provider.ConcurrentHashMap
The annotations only describe what should happen. The provider behind the CacheManager
| Annotation | Since | What the proxy does | Best for |
|---|---|---|---|
@Cacheable | 3.1 | Returns the cached value if there is one; otherwise runs the method and stores the result | Reads that are slow and called often with the same arguments |
@CachePut | 3.1 | Always runs the method, then stores the result | Updates that return the new state of an entity |
@CacheEvict | 3.1 | Runs the method, then removes one entry or all entries | Deletes, and updates that do not return the new value |
@Caching | 3.1 | Groups several of the above on one method | A change that affects more than one cache |
@CacheConfig | 4.1 | Sets the cache name and other defaults for a whole class | Avoiding the same cache name on every method |
Two later additions matter in practice. sync = true@CacheableCompletableFutureMonoFluxConcurrentMapCacheManager
A first cached method
A price lookup is the classic candidate: the same few products are asked for again and again, and the price changes rarely. The program asks for two products five times in total and counts how often the method body really runs:
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheBasics {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager("prices");
}
@Bean
PriceService priceService() {
return new PriceService();
}
}
static class PriceService {
private int loads;
public int loads() {
return loads;
}
@Cacheable("prices")
public int priceOf(String sku) {
loads++;
System.out.println(" loading " + sku + " from the database");
return sku.length() * 100;
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
PriceService service = context.getBean(PriceService.class);
System.out.println("Bean class: " + service.getClass().getName());
for (String sku : new String[] {"pen", "notebook", "pen", "pen", "notebook"}) {
System.out.println("priceOf(" + sku + ") = " + service.priceOf(sku));
}
System.out.println("Method bodies run: " + service.loads());
var cache = context.getBean(CacheManager.class).getCache("prices");
System.out.println("Cache contents: " + cache.getNativeCache());
}
}
}
Bean class: CacheBasics$PriceService$$SpringCGLIB$$0
loading pen from the database
priceOf(pen) = 300
loading notebook from the database
priceOf(notebook) = 800
priceOf(pen) = 300
priceOf(pen) = 300
priceOf(notebook) = 800
Method bodies run: 2
Cache contents: {pen=300, notebook=800}
- The bean is a
subclass of$$SpringCGLIB$$0 . Callers hold the proxy, which is what makes the cache possible.PriceService - Only the first call for each product printed "loading". The other three calls returned 300 or 800 straight from the cache, so the method body ran 2 times for 5 calls.
- The cache is a plain map: the key is the single argument,
orpen , and the value is the returned price.notebook
The counter is read through a loads()service.loads
Spring Boot needs the same @EnableCachingspring-boot-starter-cacheConcurrentMapCacheManager
Cache keys, condition and unless
The key decides which calls share an entry, so a wrong key either wastes the cache or, worse, returns one caller's data to another. This program uses one method for each key rule and then prints all six caches:
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheKeys {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
@Bean
CustomerService customerService() {
return new CustomerService();
}
}
record Customer(int id, String name) {
}
static class CustomerService {
@Cacheable("byId")
public String name(int id) {
return "customer " + id;
}
@Cacheable("byRegion")
public String list(String region, int page) {
return region + " page " + page;
}
@Cacheable(cacheNames = "byCustomer", key = "#customer.id")
public String orders(Customer customer, boolean includeArchived) {
return customer.name() + " orders";
}
@Cacheable(cacheNames = "lookups", condition = "#id > 0")
public String lookup(int id) {
return "lookup " + id;
}
@Cacheable(cacheNames = "emails", unless = "#result == null")
public String email(int id) {
return id == 2 ? null : "user" + id + "@example.com";
}
@Cacheable("phones")
public String phone(int id) {
return id == 2 ? null : "555-010" + id;
}
}
static void show(CacheManager manager, String name) {
Cache cache = manager.getCache(name);
System.out.printf("%-10s %s%n", name, cache.getNativeCache());
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
CustomerService service = context.getBean(CustomerService.class);
service.name(7);
service.list("EU", 1);
service.list("EU", 2);
service.orders(new Customer(42, "Ada"), false);
service.orders(new Customer(42, "Ada"), true);
service.lookup(5);
service.lookup(-1);
service.email(1);
service.email(2);
service.phone(1);
service.phone(2);
CacheManager manager = context.getBean(CacheManager.class);
for (String name : new String[] {"byId", "byRegion", "byCustomer", "lookups",
"emails", "phones"}) {
show(manager, name);
}
}
}
}
byId {7=customer 7}
byRegion {SimpleKey [EU, 1]=EU page 1, SimpleKey [EU, 2]=EU page 2}
byCustomer {42=Ada orders}
lookups {5=lookup 5}
emails {1=user1@example.com}
phones {1=555-0101, 2=null}
: a method with one argument uses that argument as the key, herebyId .7 : two arguments becamebyRegion andSimpleKey [EU, 1] , so page 1 and page 2 are cached separately. A method with no arguments getsSimpleKey [EU, 2] .SimpleKey.EMPTY :byCustomer picked one field of the first argument. That is shorter, but it has a cost: the second call, withkey = "#customer.id" , found the entry stored forincludeArchived = true and returned it. A custom key must include every argument that changes the result.false :lookups is checked before the call, andcondition = "#id > 0" was neither read from nor stored in the cache.lookup(-1) :emails is checked after the call, so the null for id 2 was not stored, and the next call will try again.unless = "#result == null" : withoutphones , the null for id 2 was cached.unless stores it as aConcurrentMapCacheManager marker, which prints asNullValue , so later calls return null without running the method.null
Names such as #customer#idjavac -parameterskey = "#customer.id"EL1007E: Property or field 'id' cannot be found on null#customer#a0#p0
When the key rules are more than one expression can say, register a KeyGeneratorkeyGenerator = "myGenerator"
Keeping the cache in step with the data: @CachePut and @CacheEvict
A cache that is never updated serves stale data until the application restarts. This product service keeps two caches, one by id and one by name, and shows what each kind of write does to them:
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheUpdates {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager("products", "productsByName");
}
@Bean
ProductService productService() {
return new ProductService();
}
}
record Product(int id, String name, int price) {
}
@CacheConfig(cacheNames = "products")
static class ProductService {
private final Map<Integer, Product> table = new HashMap<>();
ProductService() {
table.put(1, new Product(1, "pen", 120));
table.put(2, new Product(2, "ink", 450));
}
@Cacheable
public Product find(int id) {
System.out.println(" SELECT product " + id);
return table.get(id);
}
public void changePriceWithoutCacheAnnotation(int id, int price) {
Product p = table.get(id);
table.put(id, new Product(id, p.name(), price));
}
@CachePut(key = "#product.id")
public Product save(Product product) {
System.out.println(" UPDATE product " + product.id());
table.put(product.id(), product);
return product;
}
@Caching(evict = {
@CacheEvict(key = "#id"),
@CacheEvict(cacheNames = "productsByName", allEntries = true)
})
public void delete(int id) {
System.out.println(" DELETE product " + id);
table.remove(id);
}
@Cacheable("productsByName")
public Product findByName(String name) {
System.out.println(" SELECT product named " + name);
return table.values().stream()
.filter(p -> p.name().equals(name)).findFirst().orElse(null);
}
@CacheEvict(allEntries = true)
public void reloadAll() {
System.out.println(" clearing the products cache");
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
ProductService service = context.getBean(ProductService.class);
CacheManager caches = context.getBean(CacheManager.class);
System.out.println("1. find(1) twice:");
service.find(1);
System.out.println(" " + service.find(1));
System.out.println("2. price changed by a method with no cache annotation:");
service.changePriceWithoutCacheAnnotation(1, 99);
System.out.println(" find(1) = " + service.find(1) + " (stale)");
System.out.println("3. save() with @CachePut:");
service.save(new Product(1, "pen", 150));
System.out.println(" find(1) = " + service.find(1));
System.out.println("4. delete(2) evicts from two caches:");
service.find(2);
service.findByName("ink");
service.delete(2);
System.out.println(" products " + caches.getCache("products").getNativeCache());
System.out.println(" productsByName "
+ caches.getCache("productsByName").getNativeCache());
System.out.println("5. reloadAll() with allEntries = true:");
service.reloadAll();
System.out.println(" products " + caches.getCache("products").getNativeCache());
}
}
}
1. find(1) twice:
SELECT product 1
Product[id=1, name=pen, price=120]
2. price changed by a method with no cache annotation:
find(1) = Product[id=1, name=pen, price=120] (stale)
3. save() with @CachePut:
UPDATE product 1
find(1) = Product[id=1, name=pen, price=150]
4. delete(2) evicts from two caches:
SELECT product 2
SELECT product named ink
DELETE product 2
products {1=Product[id=1, name=pen, price=150]}
productsByName {}
5. reloadAll() with allEntries = true:
clearing the products cache
products {}
- Step 1 printed
once for two calls: the second call was a cache hit.SELECT product 1 - Step 2 changed the price to 99 through a method with no cache annotation. The table now says 99, but
still returned 120 from the cache. Every write path has to tell the cache, including batch jobs, admin tools and direct SQL, which the cache never sees.find(1) - Step 3:
always runs the method, then stores its return value under@CachePut . The next#product.id returned the new price, 150, without afind(1) .SELECT - Step 4:
combined two evictions. Product 2 left the@Caching cache by key, andproducts emptiedallEntries = true , because the name cache cannot be cleaned by id.productsByName - Step 5:
cleared the wholereloadAll cache, the cache named once inproducts .@CacheConfig
An eviction runs after the method returns, and only if it returns normally. If the method throws, the entry stays. beforeInvocation = true
Prefer @CacheEvict@CachePut@CachePut@Cacheable@Cacheable@CachePut
Traps: self-invocation, shared objects and exceptions
Three problems appear in real applications more than any others. This program shows each one running:
import java.util.ArrayList;
import java.util.List;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheTraps {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
@Bean
CatalogService catalogService() {
return new CatalogService();
}
}
static class CatalogService {
private int tagLoads;
private int rateCalls;
@Cacheable("tags")
public List<String> tags(String product) {
tagLoads++;
return new ArrayList<>(List.of("new", "sale"));
}
public List<String> tagsInUpperCase(String product) {
return tags(product).stream().map(String::toUpperCase).toList();
}
@Cacheable("rates")
public double exchangeRate(String currency) {
rateCalls++;
if (rateCalls == 1) {
throw new IllegalStateException("rate service timed out");
}
return 1.08;
}
public int tagLoads() {
return tagLoads;
}
public int rateCalls() {
return rateCalls;
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
CatalogService service = context.getBean(CatalogService.class);
System.out.println("1. Call on this from inside the bean:");
service.tagsInUpperCase("pen");
service.tagsInUpperCase("pen");
System.out.println(" method body ran " + service.tagLoads() + " times");
System.out.println("2. Caller changes the cached list:");
List<String> first = service.tags("ink");
first.add("clearance");
System.out.println(" next caller gets " + service.tags("ink"));
System.out.println("3. Exception on the first call:");
try {
service.exchangeRate("EUR");
} catch (IllegalStateException e) {
System.out.println(" caller sees " + e.getMessage());
}
System.out.println(" second call returns " + service.exchangeRate("EUR")
+ ", method body ran " + service.rateCalls() + " times");
}
}
}
1. Call on this from inside the bean:
method body ran 2 times
2. Caller changes the cached list:
next caller gets [new, sale, clearance]
3. Exception on the first call:
caller sees rate service timed out
second call returns 1.08, method body ran 2 times
- Case 1:
callstagsInUpperCase ontags , which goes straight to the object and not through the proxy. The cached method ran 2 times for 2 calls, so the cache did nothing. The fix is the same as for transactions: call the cached method from another bean. ThethisSpring AOP page explains why. - Case 2: the caller added
to the list it received, and the next caller sawclearance . An in-memory cache returns the stored object itself, so every caller shares it. Return immutable values, such as records and[new, sale, clearance] , from cached methods.List.copyOf - Case 3: the first call threw, and nothing was cached. The second call ran the method again and returned 1.08. Exceptions are never cached, which is usually what you want, but it means a failing backend gets every request.
When the cached values cannot be made immutable, ConcurrentMapCacheManager
import java.util.ArrayList;
import java.util.List;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class StoreByValue {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
ConcurrentMapCacheManager manager = new ConcurrentMapCacheManager();
manager.setStoreByValue(true);
return manager;
}
@Bean
CatalogService catalogService() {
return new CatalogService();
}
}
static class CatalogService {
@Cacheable("tags")
public List<String> tags(String product) {
return new ArrayList<>(List.of("new", "sale"));
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
CatalogService service = context.getBean(CatalogService.class);
List<String> first = service.tags("ink");
first.add("clearance");
List<String> second = service.tags("ink");
System.out.println("first caller changed its copy: " + first);
System.out.println("next caller gets : " + second);
System.out.println("same object? : " + (first == second));
}
}
}
first caller changed its copy: [new, sale, clearance]
next caller gets : [new, sale]
same object? : false
- With
, each read returns a new copy, so the second caller gotsetStoreByValue(true) and the two lists are different objects.[new, sale] - The values must be
, and every read pays for deserialization. Redis and other remote caches always work this way, because the value has to cross the network. A shared-object bug can therefore appear or disappear when an application moves from a local cache to Redis.Serializable
Many callers, one miss: sync = true
When a popular entry expires, every request that arrives before it is reloaded misses at the same time and runs the slow method. This is called a cache stampede. To make the overlap certain rather than likely, each load in this program waits up to one second for the other callers to arrive:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheSync {
static final int CALLERS = 8;
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
@Bean
ReportService reportService() {
return new ReportService();
}
}
static class ReportService {
final AtomicInteger plainLoads = new AtomicInteger();
final AtomicInteger syncLoads = new AtomicInteger();
CountDownLatch plainArrived = new CountDownLatch(CALLERS);
CountDownLatch syncArrived = new CountDownLatch(CALLERS);
// Each load waits up to one second for the other callers to arrive too,
// so that every caller is inside the method at the same time if it can be.
static String slowLoad(CountDownLatch arrived) {
arrived.countDown();
try {
arrived.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "report";
}
@Cacheable("plain")
public String plain(String day) {
plainLoads.incrementAndGet();
return slowLoad(plainArrived);
}
@Cacheable(cacheNames = "synced", sync = true)
public String synced(String day) {
syncLoads.incrementAndGet();
return slowLoad(syncArrived);
}
public int plainLoads() {
return plainLoads.get();
}
public int syncLoads() {
return syncLoads.get();
}
}
static void hammer(Runnable call) throws InterruptedException {
try (ExecutorService pool = Executors.newFixedThreadPool(CALLERS)) {
for (int i = 0; i < CALLERS; i++) {
pool.submit(call);
}
}
}
public static void main(String[] args) throws InterruptedException {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
ReportService service = context.getBean(ReportService.class);
hammer(() -> service.plain("2026-11-14"));
System.out.println(CALLERS + " callers, sync = false: method ran "
+ service.plainLoads() + " times");
hammer(() -> service.synced("2026-11-14"));
System.out.println(CALLERS + " callers, sync = true : method ran "
+ service.syncLoads() + " times");
}
}
}
8 callers, sync = false: method ran 8 times
8 callers, sync = true : method ran 1 times
- Without
, all 8 callers found no entry, so the method ran 8 times. Against a database, that is 8 identical queries at once for a value that only one of them needed to load.sync - With
, the method ran once. The other 7 callers waited for the first one to finish and then received its result from the cache. The single load waited the full second here, because the other callers never entered the method.sync = true
The lock is per key and per JVM: with 4 instances of an application, up to 4 loads can still run at once. sync = trueunless
Caching asynchronous results
Since Spring Framework 6.1, the proxy understands methods that return CompletableFuture
import java.util.concurrent.CompletableFuture;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class CacheAsync {
@Configuration
@EnableCaching
static class Config {
@Bean
CacheManager cacheManager() {
return new ConcurrentMapCacheManager("weather");
}
@Bean
WeatherClient weatherClient() {
return new WeatherClient();
}
}
static class WeatherClient {
private int calls;
@Cacheable("weather")
public CompletableFuture<String> forecast(String city) {
calls++;
System.out.println(" remote call " + calls + " for " + city);
if (city.equals("Atlantis")) {
return CompletableFuture.failedFuture(new IllegalStateException("no such city"));
}
return CompletableFuture.supplyAsync(() -> city + ": 14C, cloudy");
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
WeatherClient client = context.getBean(WeatherClient.class);
System.out.println(client.forecast("Oslo").join());
System.out.println(client.forecast("Oslo").join());
for (int i = 0; i < 2; i++) {
client.forecast("Atlantis")
.exceptionally(e -> "failed: " + e.getMessage())
.thenAccept(System.out::println).join();
}
Object stored = context.getBean(CacheManager.class).getCache("weather")
.getNativeCache();
System.out.println("Cache contents: " + stored);
}
}
}
remote call 1 for Oslo
Oslo: 14C, cloudy
Oslo: 14C, cloudy
remote call 2 for Atlantis
failed: java.lang.IllegalStateException: no such city
remote call 3 for Atlantis
failed: java.lang.IllegalStateException: no such city
Cache contents: {Oslo=Oslo: 14C, cloudy}
- The second request for Oslo made no remote call. The proxy returned a new completed future holding the cached value.
- The cache holds
, the string itself, not a future. A remote cache can therefore store it like any other value.Oslo=Oslo: 14C, cloudy - The failed future for Atlantis was not cached, so the second request made remote call 3. A failure behaves like a thrown exception in a normal method.
Reactive types work the same way: a MonoFluxListConcurrentMapCacheManagerCaffeineCacheManagersetAsyncCacheMode(true)
Choosing a cache provider
ConcurrentMapCacheManager
# Caffeine: an in-process cache with a size limit and expiry
spring.cache.type=caffeine
spring.cache.cache-names=prices,products
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m
# Redis: one cache shared by every instance of the application
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
- Caffeine: keeps entries in the same JVM, so reads are fast, but each instance has its own copy. After an update, other instances serve the old value until their entry expires.
- Redis: one cache for all instances, so an eviction takes effect everywhere. Every read is a network call and every value is serialized. The
Spring Redis page covers the setup. - JCache (JSR-107): a standard API that Ehcache, Hazelcast and Infinispan implement, for teams that already use one of them.
Spring Boot picks a provider from the classpath, in this order: a generic CacheConcurrentHashMapspring.cache.typespring.cache.type=none@EnableCaching
Always set an expiry. A time to live puts an upper limit on how stale an entry can get, even when an eviction is missed.
Choosing the right annotation and setting
| Situation | Use |
|---|---|
| A slow read called often with the same arguments | @Cacheable |
| An update that returns the new entity | @CachePut |
| A delete, or an update you are not sure about | @CacheEvictallEntries = true |
| One change that affects several caches | @Caching |
| Results that should not be cached, such as null | unless = "#result == null" |
| Arguments that should bypass the cache | condition |
| Expensive loads of popular keys | sync = true |
| A single application instance, data with a size limit | Caffeine with maximumSizeexpireAfterWrite |
| Several instances that must see the same data | Redis with time-to-live |
| Small, fixed reference data | ConcurrentMapCacheManager |
Most caching bugs on this page come from four rules: calls on this