Chapter 11. Using the CDI Extension


Data Grid provides an extension that integrates with the CDI (Contexts and Dependency Injection) programming model and allows you to:

  • Configure and inject caches into CDI Beans and Java EE components.
  • Configure cache managers.
  • Receive cache and cache manager level events.

11.1. CDI Dependencies

Update your pom.xml with one of the following dependencies to include the Data Grid CDI extension in your project:

Embedded (Library) Mode

<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-cdi-embedded</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

Server Mode

<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-cdi-remote</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

11.2. Injecting Embedded Caches

Set up CDI beans to inject embedded caches.

Procedure

  1. Create a cache qualifier annotation.

    ...
    import jakarta.inject.Qualifier;
    
    @Qualifier
    @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface GreetingCache { 
    1
    
    }
    Copy to Clipboard Toggle word wrap
    1
    Creates a @GreetingCache qualifier.
  2. Add a producer method that defines the cache configuration.

    ...
    import org.infinispan.configuration.cache.Configuration;
    import org.infinispan.configuration.cache.ConfigurationBuilder;
    import org.infinispan.cdi.ConfigureCache;
    import jakarta.transaction.inject.Produces;
    
    public class Config {
    
        @ConfigureCache("mygreetingcache") 
    1
    
        @GreetingCache 
    2
    
        @Produces
        public Configuration greetingCacheConfiguration() {
            return new ConfigurationBuilder()
                        .memory()
                            .size(1000)
                        .build();
        }
    }
    Copy to Clipboard Toggle word wrap
    1
    Names the cache to inject.
    2
    Adds the cache qualifier.
  3. Add a producer method that creates a clustered Cache Manager, if required

    ...
    package org.infinispan.configuration.global.GlobalConfigurationBuilder;
    
    public class Config {
    
        @GreetingCache 
    1
    
        @Produces
        @ApplicationScoped 
    2
    
        public EmbeddedCacheManager defaultClusteredCacheManager() { 
    3
    
          return new DefaultCacheManager(
            new GlobalConfigurationBuilder().transport().defaultTransport().build();
       }
    }
    Copy to Clipboard Toggle word wrap
    1
    Adds the cache qualifier.
    2
    Creates the bean once for the application. Producers that create Cache Managers should always include the @ApplicationScoped annotation to avoid creating multiple Cache Managers.
    3
    Creates a new DefaultCacheManager instance that is bound to the @GreetingCache qualifier.
    Note

    Cache managers are heavy weight objects. Having more than one Cache Manager running in your application can degrade performance. When injecting multiple caches, either add the qualifier of each cache to the Cache Manager producer method or do not add any qualifier.

  4. Add the @GreetingCache qualifier to your cache injection point.

    ...
    import jakarta.inject.Inject;
    
    public class GreetingService {
    
        @Inject @GreetingCache
        private Cache<String, String> cache;
    
        public String greet(String user) {
            String cachedValue = cache.get(user);
            if (cachedValue == null) {
                cachedValue = "Hello " + user;
                cache.put(user, cachedValue);
            }
            return cachedValue;
        }
    }
    Copy to Clipboard Toggle word wrap

11.3. Injecting Remote Caches

Set up CDI beans to inject remote caches.

Procedure

  1. Create a cache qualifier annotation.

    @Remote("mygreetingcache") 
    1
    
    @Qualifier
    @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RemoteGreetingCache { 
    2
    
    }
    Copy to Clipboard Toggle word wrap
    1
    names the cache to inject.
    2
    creates a @RemoteGreetingCache qualifier.
  2. Add the @RemoteGreetingCache qualifier to your cache injection point.

    public class GreetingService {
    
        @Inject @RemoteGreetingCache
        private RemoteCache<String, String> cache;
    
        public String greet(String user) {
            String cachedValue = cache.get(user);
            if (cachedValue == null) {
                cachedValue = "Hello " + user;
                cache.put(user, cachedValue);
            }
            return cachedValue;
        }
    }
    Copy to Clipboard Toggle word wrap

Tips for injecting remote caches

  • You can inject remote caches without using qualifiers.

       ...
       @Inject
       @Remote("greetingCache")
       private RemoteCache<String, String> cache;
    Copy to Clipboard Toggle word wrap
  • If you have more than one Data Grid cluster, you can create separate remote Cache Manager producers for each cluster.

    ...
    import jakarta.transaction.context.ApplicationScoped;
    
    public class Config {
    
        @RemoteGreetingCache
        @Produces
        @ApplicationScoped 
    1
    
        public ConfigurationBuilder builder = new ConfigurationBuilder(); 
    2
    
            builder.addServer().host("localhost").port(11222);
            return new RemoteCacheManager(builder.build());
        }
    }
    Copy to Clipboard Toggle word wrap
    1
    creates the bean once for the application. Producers that create Cache Managers should always include the @ApplicationScoped annotation to avoid creating multiple Cache Managers, which are heavy weight objects.
    2
    creates a new RemoteCacheManager instance that is bound to the @RemoteGreetingCache qualifier.

11.4. Receiving Cache and Cache Manager Events

You can use CDI Events to receive Cache and Cache Manager level events.

  • Use the @Observes annotation as in the following example:
import jakarta.transaction.event.Observes;
import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent;
import org.infinispan.notifications.cachelistener.event.*;

public class GreetingService {

    // Cache level events
    private void entryRemovedFromCache(@Observes CacheEntryCreatedEvent event) {
        ...
    }

    // Cache manager level events
    private void cacheStarted(@Observes CacheStartedEvent event) {
        ...
    }
}
Copy to Clipboard Toggle word wrap
Red Hat logoGithubredditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust. Explore our recent updates.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

Theme

© 2026 Red Hat
Back to top