CDI and the Java EE ecosystem

The third theme of CDI is integration. We’ve already seen how CDI helps integrate EJB and JSF, allowing EJBs to be bound directly to JSF pages. That’s just the beginning. The CDI services are integrated into the very core of the Java EE platform. Even EJB session beans can take advantage of the dependency injection, event bus, and contextual lifecycle management that CDI provides.

CDI is also designed to work in concert with technologies outside of the platform by providing integration points into the Java EE platform via an SPI. This SPI positions CDI as the foundation for a new ecosystem of portable extensions and integration with existing frameworks and technologies. The CDI services will be able to reach a diverse collection of technologies, such as business process management (BPM) engines, existing web frameworks and de facto standard component models. Of course, The Java EE platform will never be able to standardize all the interesting technologies that are used in the world of Java application development, but CDI makes it easier to use the technologies which are not yet part of the platform seamlessly within the Java EE environment.

We’re about to see how to take full advantage of the Java EE platform in an application that uses CDI. We’ll also briefly meet a set of SPIs that are provided to support portable extensions to CDI. You might not ever need to use these SPIs directly, but don’t take them for granted. You will likely be using them indirectly, every time you use a third-party extension, such as DeltaSpike.

Java EE integration

CDI is fully integrated into the Java EE environment. Beans have access to Java EE resources and JPA persistence contexts. They may be used in Unified EL expressions in JSF and JSP pages. They may even be injected into other platform components, such as servlets and message-driven Beans, which are not beans themselves.

Built-in beans

In the Java EE environment, the container provides the following built-in beans, all with the qualifier @Default:

  • the current JTA UserTransaction,

  • a Principal representing the current caller identity,

  • the default Bean Validation ValidationFactory,

  • a Validator for the default ValidationFactory,

  • HttpServletRequest, HttpSession and ServletContext

Note

The FacesContext is not injectable. You can get at it by calling FacesContext.getCurrentInstance(). Alternatively you may define the following producer method:

import jakarta.enterprise.inject.Produces;

class FacesContextProducer {
   @Produces @RequestScoped FacesContext getFacesContext() {
      return FacesContext.getCurrentInstance();
   }
}

Injecting Java EE resources into a bean

All managed beans may take advantage of Java EE component environment injection using @Resource, @EJB, @PersistenceContext, @PersistenceUnit and @WebServiceRef. We’ve already seen a couple of examples of this, though we didn’t pay much attention at the time:

@Transactional @Interceptor
public class TransactionInterceptor {
   @Resource UserTransaction transaction;

   @AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { ... }
}
@SessionScoped
public class Login implements Serializable {
   @Inject Credentials credentials;
   @PersistenceContext EntityManager userDatabase;
    ...
}

The Java EE @PostConstruct and @PreDestroy callbacks are also supported for all managed beans. The @PostConstruct method is called after all injection has been performed.

Of course, we advise that component environment injection be used to define CDI resources, and that typesafe injection be used in application code.

Calling a bean from a servlet

It’s easy to use a bean from a servlet in Java EE. Simply inject the bean using field or initializer method injection.

public class LoginServlet extends HttpServlet {
   @Inject Credentials credentials;
   @Inject Login login;

   @Override
   public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      credentials.setUsername(request.getParameter("username")):
      credentials.setPassword(request.getParameter("password")):
      login.login();
      if ( login.isLoggedIn() ) {
         response.sendRedirect("/home.jsp");
      }
      else {
         response.sendRedirect("/loginError.jsp");
      }
   }

}

Since instances of servlets are shared across all incoming threads, the bean client proxy takes care of routing method invocations from the servlet to the correct instances of Credentials and Login for the current request and HTTP session.

Calling a bean from a message-driven bean

CDI injection applies to all EJBs, even when they aren’t CDI beans. In particular, you can use CDI injection in message-driven beans, which are by nature not contextual objects.

You can even use interceptor bindings for message-driven Beans.

@Transactional @MessageDriven
public class ProcessOrder implements MessageListener {
   @Inject Inventory inventory;
   @PersistenceContext EntityManager em;

   public void onMessage(Message message) {
      ...
   }
}

Please note that there is no session or conversation context available when a message is delivered to a message-driven bean. Only @RequestScoped and @ApplicationScoped beans are available.

But how about beans which send JMS messages?

JMS endpoints

Sending messages using JMS can be quite complex, because of the number of different objects you need to deal with. For queues we have Queue, QueueConnectionFactory, QueueConnection, QueueSession and QueueSender. For topics we have Topic, TopicConnectionFactory, TopicConnection, TopicSession and TopicPublisher. Each of these objects has its own lifecycle and threading model that we need to worry about.

You can use producer fields and methods to prepare all of these resources for injection into a bean:

import jakarta.jms.ConnectionFactory;
import jakarta.jms.Queue;

public class OrderResources {
   @Resource(name="jms/ConnectionFactory")
   private ConnectionFactory connectionFactory;

   @Resource(name="jms/OrderQueue")
   private Queue orderQueue;

   @Produces @Order
   public Connection createOrderConnection() throws JMSException {
    return connectionFactory.createConnection();
   }

   public void closeOrderConnection(@Disposes @Order Connection connection)
         throws JMSException {
      connection.close();
   }

   @Produces @Order
   public Session createOrderSession(@Order Connection connection)
         throws JMSException {
      return connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
   }

   public void closeOrderSession(@Disposes @Order Session session)
         throws JMSException {
      session.close();
   }

   @Produces @Order
   public MessageProducer createOrderMessageProducer(@Order Session session)
         throws JMSException {
      return session.createProducer(orderQueue);
   }

   public void closeOrderMessageProducer(@Disposes @Order MessageProducer producer)
         throws JMSException {
      producer.close();
   }
}

In this example, we can just inject the prepared MessageProducer, Connection or QueueSession:

@Inject Order order;
@Inject @Order MessageProducer producer;
@Inject @Order Session orderSession;

public void sendMessage() {
   MapMessage msg = orderSession.createMapMessage();
   msg.setLong("orderId", order.getId());
   ...
   producer.send(msg);
}

The lifecycle of the injected JMS objects is completely controlled by the container.

Packaging and deployment

CDI doesn’t define any special deployment archive. You can package CDI beans in JARs, EJB JARs or WARs—any deployment location in the application classpath. However, the archive must be a "bean archive".

Unlike CDI 1.0, the CDI 1.1 specification recognizes two types of bean archives. The type determines the way the container discovers CDI beans in the archive.

Note
CDI 1.1 makes use of a new XSD file for beans.xml descriptor: http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd

Explicit bean archive

An explicit bean archive is an archive which contains a beans.xml file:

  • with a version number of 1.1 (or later), with the bean-discovery-mode of all, or,

  • like in CDI 1.0 – with no version number, or, that is an empty file.

It behaves just like a CDI 1.0 bean archive – i.e. Weld discovers each Java class, interface or enum in such an archive.

Note

The beans.xml file must be located at:

  • META-INF/beans.xml (for jar archives), or,

  • WEB-INF/beans.xml or WEB-INF/classes/META-INF/beans.xml (for WAR archives).

You should never place a beans.xml file in both of the WEB-INF and the WEB-INF/classes/META-INF directories. Otherwise your application would not be portable.

Trimmed bean archive

Optionally beans.xml file in explicit bean archive can include simple trim element. This trimmed bean archive means that ProcessAnnotatedType event is fired for every AnnotatedType, but only types which are annotated with a bean defining annotation or any scope annotation will become beans.

Implicit bean archive

An implicit bean archive is an archive which contains one or more bean classes with a bean defining annotation, or one or more session beans. It can also contain a beans.xml file with a version number of 1.1 (or later), with the bean-discovery-mode of annotated. Weld only discovers Java classes with a bean defining annotation within an implicit bean archive.

Note

The set of bean defining annotations contains:

  • @ApplicationScoped, @SessionScoped, @ConversationScoped and @RequestScoped annotations,

  • all other normal scope types,

  • @Interceptor and @Decorator annotations,

  • all stereotype annotations (i.e. annotations annotated with @Stereotype),

  • and the @Dependent scope annotation.

However, @Singleton is not a bean defining annotation. See 2.5.1. Bean defining annotations to learn more.

Which archive is not a bean archive

Although quite obvious, let’s sum it up:

  • an archive which contains neither a beans.xml file nor any bean class with a bean defining annotation,

  • an archive which contains a beans.xml file with the bean-discovery-mode of none.

Actually, there is one more special rule (designed to retain backward compatibility): an archive which contains a portable extension and no beans.xml is not a bean archive either. However, this is not a very common use case.

Note
For compatibility with CDI 1.0, each Java EE product (WildFly, GlassFish, etc.) must contain an option to cause an archive to be ignored by the container when no beans.xml is present. Consult specific Java EE product documentation to learn more about such option.

Embeddable EJB container

In an embeddable EJB container, beans may be deployed in any location in which EJBs may be deployed.

Portable extensions

CDI is intended to be a foundation for frameworks, extensions and integration with other technologies. Therefore, CDI exposes a set of SPIs for the use of developers of portable extensions to CDI. For example, the following kinds of extensions were envisaged by the designers of CDI:

  • integration with Business Process Management engines,

  • integration with third-party frameworks such as Spring, Seam, GWT or Wicket, and

  • new technology based upon the CDI programming model.

More formally, according to the spec:

A portable extension may integrate with the container by:

  • Providing its own beans, interceptors and decorators to the container

  • Injecting dependencies into its own objects using the dependency injection service

  • Providing a context implementation for a custom scope

  • Augmenting or overriding the annotation-based metadata with metadata from some other source

Creating an Extension

The first step in creating a portable extension is to write a class that implements Extension. This marker interface does not define any methods, but it’s needed to satisfy the requirements of Java SE’s service provider architecture.

 import jakarta.enterprise.inject.spi.Extension;

class MyExtension implements Extension { ... }

Next, we need to register our extension as a service provider by creating a file named META-INF/services/jakarta.enterprise.inject.spi.Extension, which contains the name of our extension class:

org.mydomain.extension.MyExtension

An extension is not a bean, exactly, since it is instantiated by the container during the initialization process, before any beans or contexts exist. However, it can be injected into other beans once the initialization process is complete.

@Inject
MyBean(MyExtension myExtension) {
   myExtension.doSomething();
}

And, like beans, extensions can have observer methods. Usually, the observer methods observe container lifecycle events.

Note
Weld SE allows to define so called synthetic container lifecycle event observers. Such observers do not belong to a particular extension. See also org.jboss.weld.environment.se.ContainerLifecycleObserver and Weld.addContainerLifecycleObserver().

Container lifecycle events

During the initialization process, the container fires a series of events, including:

  • BeforeBeanDiscovery

  • ProcessAnnotatedType and ProcessSyntheticAnnotatedType

  • AfterTypeDiscovery

  • ProcessInjectionTarget and ProcessProducer

  • ProcessInjectionPoint

  • ProcessBeanAttributes

  • ProcessBean, ProcessManagedBean, ProcessSessionBean, ProcessProducerMethod, ProcessProducerField and ProcessSyntheticBean

  • ProcessObserverMethod and ProcessSyntheticObserverMethod

  • AfterBeanDiscovery

  • AfterDeploymentValidation

Extensions may observe these events:

import jakarta.enterprise.inject.spi.Extension;

class MyExtension implements Extension {

   void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd) {
      Logger.global.debug("beginning the scanning process");
   }

   <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> pat) {
      Logger.global.debug("scanning type: " + pat.getAnnotatedType().getJavaClass().getName());
   }

   void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) {
      Logger.global.debug("finished the scanning process");
   }

}

In fact, the extension can do a lot more than just observe. The extension is permitted to modify the container’s metamodel and more. Here’s a very simple example:

import jakarta.enterprise.inject.spi.Extension;

class MyExtension implements Extension {

   <T> void processAnnotatedType(@Observes @WithAnnotations({Ignore.class}) ProcessAnnotatedType<T> pat) {
      /* tell the container to ignore the type if it is annotated @Ignore */
      if ( pat.getAnnotatedType().isAnnotationPresent(Ignore.class) ) pat.veto();
   }

}
Note
The @WithAnnotations annotation causes the container to deliver the ProcessAnnotatedType events only for the types which contain the specified annotation.

Container lifecycle event observer methods may inject a BeanManager:

<T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> pat, BeanManager beanManager) { ... }

An extension observer method is not allowed to inject any other object.

Configurators

CDI 2.0 introduced the Configurators API - a new way to easily configure some parts of the SPI during container lifecycle event notification. E.g. to add a qualifier to a bean, an extension can observe ProcessBeanAttributes, then obtain a configurator instance through ProcessBeanAttributes.configureBeanAttributes() and finally use BeanAttributesConfigurator.addQualifier(Annotation). No need to wrap/delegate to the original BeanAttributes. See also chapter Configurators interfaces of the CDI specification.

Weld-enriched container lifecycle events

Apart from CDI-defined lifecycle events, Weld also offers enriched observable container lifecycle events - WeldAfterBeanDiscovery and WeldProcessManagedBean.

WeldAfterBeanDiscovery

Compared to jakarta.enterprise.inject.spi.AfterBeanDiscovery, this interface adds one extra method - addInterceptor(). This method works in the same way as the aforementioned Configurators; you get back an InterceptorConfigurator instance, where you can set all the desired data. The interceptor is created automatically, once the methods exits and the configurator instance is not reusable. But if you need to create several interceptors, you can simply request several configurator instances. Here is a code snippet to demonstrate the idea:

public void afterBeanDiscovery(@Observes WeldAfterBeanDiscovery event) {

        // type level interceptor
        event.addInterceptor().intercept(InterceptionType.AROUND_INVOKE, (invocationContext) -> {
            try {
                getAnswerToLifeTheUniverseAndEverything();
                return invocationContext.proceed();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }).priority(2500).addBinding(MyTypeBinding.MyTypeBindingLiteral.INSTANCE);
}

The sample presents a simple interception use case where you supply java.util.function.Function as the interceptor body method. For more complex cases, you may also choose to use interceptWithMetadata method which accepts java.util.function.BiFunction instead. The second parameter of the BiFunction emulates @Inject @Intercepted Bean<?> allowing access to metadata.

WeldProcessManagedBean

Compared to specification defined API, WeldProcessManagedBean overrides its method for invoker creation granting access to org.jboss.weld.invoke.WeldInvokerBuilder which is an enhanced version enabling use of various transformers. This is captured in greater detail within [weldinvoker] chapter.

The BeanManager object

The nerve center for extending CDI is the BeanManager object. The BeanManager interface provides operations useful for portable extensions, e.g. lets us obtain beans, interceptors, decorators, observers and contexts programmatically. Note that some of the methods may not be called before the AfterBeanDiscovery event is fired, e.g. BeanManager.getBeans(). Furthermore, the BeanManager.getReference() and BeanManager.getInjectableReference() methods may not be called before the AfterDeploymentValidation event is fired. See also the javadoc for more details.

As already stated in Container lifecycle events, any container lifecycle event observer method can obtain an injected BeanManager reference:

void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager beanManager) { ... }

Furthermore, any bean or other Java EE component which supports injection can obtain an instance of BeanManager via injection:

@Inject BeanManager beanManager;

Alternatively, a BeanManager reference may be obtained from CDI via a static method call.

CDI.current().getBeanManager()

Java EE components may obtain an instance of BeanManager from JNDI by looking up the name java:comp/BeanManager. Any operation of BeanManager may be called at any time during the execution of the application.

Let’s study some of the interfaces exposed by the BeanManager.

The CDI class

Application components which cannot obtain a BeanManager reference via injection nor JNDI lookup can get the reference from the jakarta.enterprise.inject.spi.CDI class via a static method call:

BeanManager manager = CDI.current().getBeanManager();

The CDI class can be used directly to programmatically lookup CDI beans as described in Obtaining a contextual instance by programmatic lookup .

CDI.select(Foo.class).get()

The InjectionTarget interface

The first thing that a framework developer is going to look for in the portable extension SPI is a way to inject CDI beans into objects which are not under the control of CDI. The InjectionTarget interface makes this very easy.

Note
We recommend that frameworks let CDI take over the job of actually instantiating the framework-controlled objects. That way, the framework-controlled objects can take advantage of constructor injection. However, if the framework requires use of a constructor with a special signature, the framework will need to instantiate the object itself, and so only method and field injection will be supported.
import jakarta.enterprise.inject.spi.CDI;

...

//get the BeanManager
BeanManager beanManager = CDI.current().getBeanManager();

//CDI uses an AnnotatedType object to read the annotations of a class
AnnotatedType<SomeFrameworkComponent> type = beanManager.createAnnotatedType(SomeFrameworkComponent.class);

//The extension uses an InjectionTarget to delegate instantiation, dependency injection
//and lifecycle callbacks to the CDI container
InjectionTarget<SomeFrameworkComponent> it = beanManager.createInjectionTarget(type);

//each instance needs its own CDI CreationalContext
CreationalContext ctx = beanManager.createCreationalContext(null);

//instantiate the framework component and inject its dependencies
SomeFrameworkComponent instance = it.produce(ctx);  //call the constructor
it.inject(instance, ctx);  //call initializer methods and perform field injection
it.postConstruct(instance);  //call the @PostConstruct method

...

//destroy the framework component instance and clean up dependent objects
it.preDestroy(instance);  //call the @PreDestroy method
it.dispose(instance);  //it is now safe to discard the instance
ctx.release();  //clean up dependent objects

The Bean interface

Instances of the interface Bean represent beans. There is an instance of Bean registered with the BeanManager object for every bean in the application. There are even Bean objects representing interceptors, decorators and producer methods.

The BeanAttributes interface exposes all the interesting things we discussed in The anatomy of a bean .

public interface BeanAttributes<T> {
   public Set<Type> getTypes();
   public Set<Annotation> getQualifiers();
   public Class<? extends Annotation> getScope();
   public String getName();
   public Set<Class<? extends Annotation>> getStereotypes();
   public boolean isAlternative();
}

The Bean interface extends the BeanAttributes interface and defines everything the container needs to manage instances of a certain bean.

public interface Bean<T> extends Contextual<T>, BeanAttributes<T> {
   public Class<?> getBeanClass();
   public Set<InjectionPoint> getInjectionPoints();
   public boolean isNullable();
}

There’s an easy way to find out what beans exist in the application:

Set<Bean<?>> allBeans = beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {});

The Bean interface makes it possible for a portable extension to provide support for new kinds of beans, beyond those defined by the CDI specification. For example, we could use the Bean interface to allow objects managed by another framework to be injected into beans.

Registering a Bean

The most common kind of CDI portable extension registers a bean (or beans) with the container.

In this example, we make a framework class, FrameworkManager available for injection. To make things a bit more interesting, we’re going to delegate back to the container’s InjectionTarget to perform instantiation and injection upon the FrameworkManager instance.

import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.event.Observes;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import jakarta.enterprise.inject.spi.InjectionPoint;
...

public class FrameworkManagerExtension implements Extension {

    void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager bm) {
        event.addBean()
           /* read annotations of the class and create an InjectionTarget used to instantiate the class and inject dependencies */
           .read(bm.createAnnotatedType(FrameworkManager.class))
           .beanClass(FrameworkManager.class)
           .scope(ApplicationScoped.class)
           .name("frameworkManager");
    }

}

But a portable extension can also mess with beans that are discovered automatically by the container.

Configuring an AnnotatedType

One of the most interesting things that an extension class can do is process the annotations of a bean class before the container builds its metamodel.

Let’s start with an example of an extension that provides support for the use of @Named at the package level. The package-level name is used to qualify the EL names of all beans defined in that package. The portable extension uses the ProcessAnnotatedType event to configure the AnnotatedType object and override the value() of the @Named annotation.

import java.lang.reflect.Type;
import jakarta.enterprise.inject.spi.Extension;
import java.lang.annotation.Annotation;
...

public class QualifiedNameExtension implements Extension {

    <X> void processAnnotatedType(@Observes ProcessAnnotatedType<X> event) {

        /* wrap this to override the annotations of the class */
        final AnnotatedType<X> at = event.getAnnotatedType();

        /* Only wrap AnnotatedTypes for classes with @Named packages */
        Package pkg = at.getJavaClass().getPackage();
        if (pkg == null || !pkg.isAnnotationPresent(Named.class) ) {
            return;
        }

        String unqualifiedName = "";
        if (at.isAnnotationPresent(Named.class)) {
            unqualifiedName = at.getAnnotation(Named.class).value();
        }
        if (unqualifiedName.isEmpty()) {
            unqualifiedName = Introspector.decapitalize(at.getJavaClass().getSimpleName());
        }
        final String qualifiedName = pkg.getAnnotation(Named.class).value()
                            + '_' + unqualifiedName;

        event.configureAnnotatedType().remove((a) -> a.annotationType().equals(Named.class)).add(NamedLiteral.of(qualifiedName));
    }

}

Here’s a second example, which adds the @Alternative annotation to any class which implements a certain Service interface.

import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.Alternative;
...

class ServiceAlternativeExtension implements Extension {

   <T extends Service> void processAnnotatedType(@Observes ProcessAnnotatedType<T> event) {
      event.configureAnnotatedType().add(Alternative.Literal.INSTANCE);
   }
}

The AnnotatedType is not the only thing that can be configured/wrapped by an extension.

Overriding attributes of a bean

Configuring an AnnotatedType is a low-level approach to overriding CDI metadata by adding, removing or replacing annotations. Since version 1.1, CDI provides a higher-level facility for overriding attributes of beans discovered by the CDI container.

public interface BeanAttributes<T> {

   public Set<Type> getTypes();

   public Set<Annotation> getQualifiers();

   public Class<? extends Annotation> getScope();

   public String getName();

   public Set<Class<? extends Annotation>> getStereotypes();

   public boolean isAlternative();

}

The BeanAttributes interface exposes attributes of a bean. The container fires a ProcessBeanAttributes event for each enabled bean, interceptor and decorator before this object is registered. Similarly to the ProcessAnnotatedType, this event allows an extension to modify attributes of a bean or to veto the bean entirely.

public interface ProcessBeanAttributes<T> {

    public Annotated getAnnotated();

    public BeanAttributes<T> getBeanAttributes();

    public BeanAttributesConfigurator<T> configureBeanAttributes();

    public void setBeanAttributes(BeanAttributes<T> beanAttributes);

    public void addDefinitionError(Throwable t);

    public void veto();

}

The BeanManager also provides two utility methods for creating the BeanAttributes object from scratch:

public <T> BeanAttributes<T> createBeanAttributes(AnnotatedType<T> type);

public BeanAttributes<?> createBeanAttributes(AnnotatedMember<?> type);

Wrapping an InjectionTarget

The InjectionTarget interface exposes operations for producing and disposing an instance of a component, injecting its dependencies and invoking its lifecycle callbacks. A portable extension may wrap the InjectionTarget for any Java EE component that supports injection, allowing it to intercept any of these operations when they are invoked by the container.

Here’s a CDI portable extension that reads values from properties files and configures fields of Java EE components, including servlets, EJBs, managed beans, interceptors and more. In this example, properties for a class such as org.mydomain.blog.Blogger go in a resource named org/mydomain/blog/Blogger.properties, and the name of a property must match the name of the field to be configured. So Blogger.properties could contain:

firstName=Gavin
lastName=King

The portable extension works by wrapping the containers InjectionTarget and setting field values from the inject() method.

import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.InjectionPoint;

public class ConfigExtension implements Extension {

    <X> void processInjectionTarget(@Observes ProcessInjectionTarget<X> pit) {

          /* wrap this to intercept the component lifecycle */
         final InjectionTarget<X> it = pit.getInjectionTarget();

        final Map<Field, Object> configuredValues = new HashMap<Field, Object>();

        /* use this to read annotations of the class and its members */
        AnnotatedType<X> at = pit.getAnnotatedType();

        /* read the properties file */
        String propsFileName = at.getJavaClass().getSimpleName() + ".properties";
        InputStream stream = at.getJavaClass().getResourceAsStream(propsFileName);
        if (stream!=null) {

            try {
                Properties props = new Properties();
                props.load(stream);
                for (Map.Entry<Object, Object> property : props.entrySet()) {
                    String fieldName = property.getKey().toString();
                    Object value = property.getValue();
                    try {
                        Field field = at.getJavaClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        if ( field.getType().isAssignableFrom( value.getClass() ) ) {
                            configuredValues.put(field, value);
                        }
                        else {
                            /* TODO: do type conversion automatically */
                            pit.addDefinitionError( new InjectionException(
                                   "field is not of type String: " + field ) );
                        }
                    }
                    catch (NoSuchFieldException nsfe) {
                        pit.addDefinitionError(nsfe);
                    }
                    finally {
                        stream.close();
                    }
                }
            }
            catch (IOException ioe) {
                pit.addDefinitionError(ioe);
            }
        }

        InjectionTarget<X> wrapped = new InjectionTarget<X>() {

            @Override
            public void inject(X instance, CreationalContext<X> ctx) {
                it.inject(instance, ctx);

                /* set the values onto the new instance of the component */
                for (Map.Entry<Field, Object> configuredValue: configuredValues.entrySet()) {
                    try {
                        configuredValue.getKey().set(instance, configuredValue.getValue());
                    }
                    catch (Exception e) {
                        throw new InjectionException(e);
                    }
                }
            }

            @Override
            public void postConstruct(X instance) {
                it.postConstruct(instance);
            }

            @Override
            public void preDestroy(X instance) {
                it.dispose(instance);
            }

            @Override
            public void dispose(X instance) {
                it.dispose(instance);
            }

            @Override
            public Set<InjectionPoint> getInjectionPoints() {
                return it.getInjectionPoints();
            }

            @Override
            public X produce(CreationalContext<X> ctx) {
                return it.produce(ctx);
            }

        };

        pit.setInjectionTarget(wrapped);

    }

}

Overriding InjectionPoint

CDI provides a way to override the metadata of an InjectionPoint. This works similarly to how metadata of a bean may be overridden using BeanAttributes.

For every injection point of each component supporting injection Weld fires an event of type jakarta.enterprise.inject.spi.ProcessInjectionPoint

public interface ProcessInjectionPoint<T, X> {
    public InjectionPoint getInjectionPoint();
    public InjectionPointConfigurator configureInjectionPoint();
    public void setInjectionPoint(InjectionPoint injectionPoint);
    public void addDefinitionError(Throwable t);
}

An extension may either completely override the injection point metadata or alter it by wrapping the InjectionPoint object obtained from ProcessInjectionPoint.getInjectionPoint()

There’s a lot more to the portable extension SPI than what we’ve discussed here. Check out the CDI spec or Javadoc for more information. For now, we’ll just mention one more extension point.

Manipulating interceptors, decorators and alternatives enabled for an application

An event of type jakarta.enterprise.inject.spi.AfterTypeDiscovery is fired when the container has fully completed the type discovery process and before it begins the bean discovery process.

public interface AfterTypeDiscovery {
    public List<Class<?>> getAlternatives();
    public List<Class<?>> getInterceptors();
    public List<Class<?>> getDecorators();
    public void addAnnotatedType(AnnotatedType<?> type, String id);
}

This event exposes a list of enabled alternatives, interceptors and decorators. Extensions may manipulate these collections directly to add, remove or change the order of the enabled records.

In addition, an AnnotatedType can be added to the types which will be scanned during bean discovery, with an identifier, which allows multiple annotated types, based on the same underlying type, to be defined.

The Context and AlterableContext interfaces

The Context and AlterableContext interface support addition of new scopes to CDI, or extension of the built-in scopes to new environments.

public interface Context {
   public Class<? extends Annotation> getScope();
   public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext);
   public <T> T get(Contextual<T> contextual);
   boolean isActive();
}

For example, we might implement Context to add a business process scope to CDI, or to add support for the conversation scope to an application that uses Wicket.

import jakarta.enterprise.context.spi.Context;

public interface AlterableContext extends Context {
    public void destroy(Contextual<?> contextual);
}

AlterableContext was introduced in CDI 1.1. The destroy method allows an application to remove instances of contextual objects from a context.

For more information on implementing a custom context see this blog post or the Command context example.

Build Compatible extensions

Since CDI 4, users can leverage Build Compatible extensions as an alternative to Portable extensions. Both extension models are targeting the same set of use cases and can users can choose either model or even combine both.

As name suggests, Build Compatible extensions are tailored to run in more constrained environments and as such have to sacrifice some functionality and user-friendliness in order to retain portability across very different environments. For example, Build Compatible extension cannot be injected as a bean at runtime and therefore cannot be used to carry information gathered during CDI bootstrap into later stages of your application. Another notable difference is that unlike Portable extensions and their reflection-heavy model (for instance AnnotatedType), Build Compatible extensions use an entirely different language model, that has a reflection-free API.

Weld supports Build Compatible extensions and their language model but does so through usage of reflection and executes these extensions by binding their lifecycle calls to a specialized Portable extension. Since Weld is a CDI Full implementation, it is recommended to keep using Portable extensions over Build Compatible extensions.

The support works out of the box for Weld SE and Weld Servlet but for any other environments and custom integrations, it is up to integrators to make sure the support is included. Take a look at org.jboss.weld.lite.extension.translator.LiteExtensionTranslator and org.jboss.weld.lite.extension.translator.BuildCompatibleExtensionLoader in case you want to learn more about this topic.

Users can also choose to provide the same functionality in both variants - a Portable extension and a Build Compatible extension. It is then possible to annotate the Build Compatible variant with @jakarta.enterprise.inject.build.compatible.spi.SkipIfPortableExtensionPresent which will automatically disable the Build Compatible variant in favor of Portable extension variant in CDI Full environments.

Build Compatible extension have an extensive Javadoc describing how to use them; a good starting point is the jakarta.enterprise.inject.build.compatible.spi.BuildCompatibleExtension interface. Further documentation is available in dedicated CDI specification chapter.

Next steps

A lot of additional information on CDI can be found online. Regardless, the CDI specification remains the authority for information on CDI. The spec is fairly readable and it covers many details we’ve skipped over here.It is available on the at the Jakarta website (CDI 4.0).

The CDI compatible implementation, Weld, is being developed by the Weld team.

We encourage you to follow the weld-dev mailing list and to get involved in development. If you are reading this guide, you likely have something to offer.