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 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 @Transactional:

  • A proxy: @EnableCaching makes Spring wrap every bean that has cache annotations. Callers get the proxy, and the proxy decides whether the real method runs at all.
  • 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 SimpleKey that holds all of them.
  • A cache manager: each Cache has a name, such as "prices", and behaves like a map from key to value. The CacheManager decides where the data lives: a ConcurrentHashMap in the same JVM, Caffeine, Redis, or any JCache provider.

The annotations only describe what should happen. The provider behind the CacheManager decides how long entries live, how many are kept, and whether other servers can see them. That split lets you start with an in-memory map and move to Redis later without changing the annotated methods.

The cache annotations
AnnotationSinceWhat the proxy doesBest for
@Cacheable3.1Returns the cached value if there is one; otherwise runs the method and stores the resultReads that are slow and called often with the same arguments
@CachePut3.1Always runs the method, then stores the resultUpdates that return the new state of an entity
@CacheEvict3.1Runs the method, then removes one entry or all entriesDeletes, and updates that do not return the new value
@Caching3.1Groups several of the above on one methodA change that affects more than one cache
@CacheConfig4.1Sets the cache name and other defaults for a whole classAvoiding the same cache name on every method

Two later additions matter in practice. sync = true on @Cacheable, from Spring Framework 4.3, lets one thread compute a missing value while the others wait. And since Spring Framework 6.1, methods that return CompletableFuture, Mono or Flux cache the value they produce, not the wrapper. Every program on this page runs Spring Framework 7.0 with ConcurrentMapCacheManager and no Spring Boot; the annotations behave the same in a Boot application.

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:

Java
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());
        }
    }
}
Output
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 $$SpringCGLIB$$0 subclass of PriceService. Callers hold the proxy, which is what makes the cache possible.
  • 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, pen or notebook, and the value is the returned price.

The counter is read through a loads() method rather than the field. A CGLIB proxy is a separate object with its own copy of the fields, so reading service.loads directly on the proxy prints 0, while calling a public method on the proxy forwards the call to the real bean.

Spring Boot needs the same @EnableCaching. If you add spring-boot-starter-cache without another provider on the classpath, Boot creates a ConcurrentMapCacheManager like the one here.

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:

Java
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);
            }
        }
    }
}
Output
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}
  • byId: a method with one argument uses that argument as the key, here 7.
  • byRegion: two arguments became SimpleKey [EU, 1] and SimpleKey [EU, 2], so page 1 and page 2 are cached separately. A method with no arguments gets SimpleKey.EMPTY.
  • byCustomer: key = "#customer.id" picked one field of the first argument. That is shorter, but it has a cost: the second call, with includeArchived = true, found the entry stored for false and returned it. A custom key must include every argument that changes the result.
  • lookups: condition = "#id > 0" is checked before the call, and lookup(-1) was neither read from nor stored in the cache.
  • emails: unless = "#result == null" is checked after the call, so the null for id 2 was not stored, and the next call will try again.
  • phones: without unless, the null for id 2 was cached. ConcurrentMapCacheManager stores it as a NullValue marker, which prints as null, so later calls return null without running the method.

Names such as #customer and #id come from the compiled parameter names, which exist only when the code is compiled with javac -parameters. The Spring Boot Maven and Gradle plugins turn that flag on, and these programs were compiled with it. Compiled without it, key = "#customer.id" fails with EL1007E: Property or field 'id' cannot be found on null, because #customer resolves to null. The index forms #a0 and #p0 work without the flag.

When the key rules are more than one expression can say, register a KeyGenerator bean and name it with keyGenerator = "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:

Java
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());
        }
    }
}
Output
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 SELECT product 1 once for two calls: the second call was a cache hit.
  • Step 2 changed the price to 99 through a method with no cache annotation. The table now says 99, but find(1) 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.
  • Step 3: @CachePut always runs the method, then stores its return value under #product.id. The next find(1) returned the new price, 150, without a SELECT.
  • Step 4: @Caching combined two evictions. Product 2 left the products cache by key, and allEntries = true emptied productsByName, because the name cache cannot be cleaned by id.
  • Step 5: reloadAll cleared the whole products cache, the cache named once in @CacheConfig.

An eviction runs after the method returns, and only if it returns normally. If the method throws, the entry stays. beforeInvocation = true evicts before the method runs, whatever happens next.

Prefer @CacheEvict to @CachePut when in doubt. An evicted entry is simply reloaded on the next read. A @CachePut stores whatever the method returned, which is wrong if that differs from what @Cacheable would load. Do not put @Cacheable and @CachePut on the same method.

Traps: self-invocation, shared objects and exceptions

Three problems appear in real applications more than any others. This program shows each one running:

Java
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");
        }
    }
}
Output
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: tagsInUpperCase calls tags on this, 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. The Spring AOP page explains why.
  • Case 2: the caller added clearance to the list it received, and the next caller saw [new, sale, clearance]. An in-memory cache returns the stored object itself, so every caller shares it. Return immutable values, such as records and List.copyOf, from cached methods.
  • 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 can store a serialized copy instead of the object:

Java
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));
        }
    }
}
Output
first caller changed its copy: [new, sale, clearance]
next caller gets             : [new, sale]
same object?                 : false
  • With setStoreByValue(true), each read returns a new copy, so the second caller got [new, sale] and the two lists are different objects.
  • The values must be Serializable, 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.

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:

Java
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");
        }
    }
}
Output
8 callers, sync = false: method ran 8 times
8 callers, sync = true : method ran 1 times
  • Without sync, 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.
  • With sync = true, 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.

The lock is per key and per JVM: with 4 instances of an application, up to 4 loads can still run at once. sync = true also has rules: it allows only one cache name, it cannot be combined with unless, and it cannot be mixed with other cache annotations on the same method. All the cache managers in Spring Framework support it; check your provider's documentation for others.

Caching asynchronous results

Since Spring Framework 6.1, the proxy understands methods that return CompletableFuture: it waits for the future to complete and caches the value inside it. A weather client is a good example, because the remote call is slow and some cities do not exist:

Java
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);
        }
    }
}
Output
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 Oslo=Oslo: 14C, cloudy, the string itself, not a future. A remote cache can therefore store it like any other value.
  • 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 Mono caches its value, and a Flux caches a List of all its elements once it completes. The cache must support asynchronous retrieval. ConcurrentMapCacheManager does, and CaffeineCacheManager does once setAsyncCacheMode(true) is set.

Choosing a cache provider

ConcurrentMapCacheManager has no size limit and no expiry: entries stay until they are evicted or the application stops. That is fine for small, fixed data such as country codes, and a memory leak for anything keyed by user or request. Production applications use a provider that limits size and age. These configurations were checked against the Spring Boot 4.1 reference documentation but were not run here, because they need Caffeine or a Redis server:

Properties
# 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 Cache bean, JCache, Hazelcast, Infinispan, Couchbase, Redis, Caffeine, Cache2k, and finally the simple ConcurrentHashMap. Set spring.cache.type to choose one explicitly, or spring.cache.type=none to switch caching off in tests. Boot's documentation also advises putting @EnableCaching on a separate configuration class rather than the main application class, so that tests can leave it out.

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

Common caching situations and what fits them
SituationUse
A slow read called often with the same arguments@Cacheable
An update that returns the new entity@CachePut with a key that matches the read
A delete, or an update you are not sure about@CacheEvict, with allEntries = true for caches you cannot clean by key
One change that affects several caches@Caching
Results that should not be cached, such as nullunless = "#result == null"
Arguments that should bypass the cachecondition
Expensive loads of popular keyssync = true
A single application instance, data with a size limitCaffeine with maximumSize and expireAfterWrite
Several instances that must see the same dataRedis with time-to-live
Small, fixed reference dataConcurrentMapCacheManager

Most caching bugs on this page come from four rules: calls on this skip the cache, a custom key must include every argument that changes the result, every write path must evict or update, and a local cache shares one object between all callers. Caching works best for data that is read far more often than it changes. For data that changes on most requests, keeping the cache correct usually costs more than it saves. Related pages: Spring @Transactional, which uses the same proxy mechanism, and Spring Redis.