Spring @Cacheable with Embedded Infinispan

What You Will Learn

How to configure Spring’s CacheManager with an embedded Infinispan implementation and use @Cacheable to transparently cache slow method results.

Prerequisites

  • Java 17+

  • Spring Framework

Step 1: Add Dependencies

Add the Infinispan Spring embedded integration and Spring Context:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-spring7-embedded</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
</dependency>

Step 2: Configure the Spring CacheManager

Create a Spring configuration that provides the Infinispan-backed CacheManager and enables caching:

    @Configuration
    @EnableCaching
    public static class SpringConfiguration {

        @Bean
        public SpringEmbeddedCacheManagerFactoryBean springCache() {
            return new SpringEmbeddedCacheManagerFactoryBean();
        }

        @Bean
        public CachedObject cachedObject() {
            return new CachedObject();
        }
    }

Step 3: Annotate Slow Methods with @Cacheable

Apply @Cacheable to methods whose results should be cached. The first call executes the method; subsequent calls return the cached result:

    public static class CachedObject {

        @Cacheable(value = "default")
        public String verySlowMethod() {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "Spring and Infinispan will speed this one up!";
        }
    }

Step 4: Run the Tutorial

mvn package exec:exec@spring-caching

You should see output like:

Returned: "Spring and Infinispan will speed this one up!" in 5 s
Returned: "Spring and Infinispan will speed this one up!" in 0 s

The first call takes 5 seconds. The second call returns instantly from the Infinispan cache.

What’s Next