Next Presso (CDI, Java EE and friends)

CDI, the SPI who loved me

Posted by Antoine Sabot-Durand on Feb 20, 2016 | Comments

CDI users ask me very often why they should adopt CDI and stop using their old framework or way of doing their developments. The answer to this question can be found in advanced CDI stuff: extension mechanism and CDI SPI.

Yes, CDI true killing feature is not accessible out of the box and you have to dig into the spec to grab its power. Unfortunately, the way it’s introduced and explained in the specification document doesn’t make it particularly shine.

With this article and a coming one on portable extensions, I’ll try to fix that and help beginner users to get an overview of the power they’ll have if they invest time in learning CDI SPI.

I’ll try to show you all the aspects of the CDI SPI and how you can use part of it in your day to day work. In this article I’ll use the term "usual code" in opposition to portable extension code to differentiate standard development from development to extend CDI. At the end of the day you’ll see how much the CDI SPI loves developers ;).

What is this SPI?

CDI SPI is the introspection part of the spec allowing developers to access meta-information about CDI concepts (Beans, events, injection point, interceptors, etc…​)

While some of you may be more familiar with the term API (Application Programming Interface), the CDI specification is mainly built on a SPI concept (Service Provider Interface). So what’s the difference?

  • An API is the description of classes/interfaces/methods/…​ that you call and use to achieve a goal

  • An SPI is the description of classes/interfaces/methods/…​ that you extend and implement to achieve a goal

To make short, CDI provides interfaces that you implement (or that spec implementation implement for you) to perform a specific task. Access to these implementation are usually done through injection or event observation but you’ll have on the rare occasion to create your own implementation.

To ease the understand of the SPI, I’d like to split in 4 parts:

  • CDI entry points

  • Type meta-model

  • CDI meta-model

  • SPI dedicated to extensions

This division is a subjective approach I use to introduce elements of the SPI, it doesn’t reflect organisation of CDI packages or documentation.

Let’s explore these different parts

SPI providing CDI entry points

Usually, when you develop a Java EE application you don’t have to bother "entering" in CDI bean graph. It’s automatically done from the UI (via expression language), CDI event triggered automatically at boot time or EJB call.

But sometimes, you may need to access CDI from non CDI code or plug non CDI code to CDI beans at run time. This part of the SPI gives you the tools to do it.

entry points

BeanManager and CDI

In CDI 1.0 the only solution you had to access CDI bean graph was to retrieve the BeanManager from JNDI

BeanManager bm = null;
try {
    InitialContext context = new InitialContext();
    bm = (BeanManager) context.lookup("java:comp/BeanManager");
} catch (Exception e) {

The BeanManager is a central interface in CDI SPI, giving access to all meta-data and instantiated components in your application.

Checking its section in spec or its javadoc gives a complete overview of all the features it contains.

The main reason for developers to access CDI from non CDI code is to request a Bean instance to enter the CDI bean graph. Doing so with the BeanManager is a bit verbose.

BeanManager bm = null;
try {
    InitialContext context = new InitialContext();
    bm = (BeanManager) context.lookup("java:comp/BeanManager"); (1)
} catch (Exception e) {
Set<Bean<?>> beans = bm.getBeans(MyService.class); (2)
Bean<?> bean =  bm.resolve(beans); (3)
CreationalContext<MyService> ctx = bm.createCreationalContext(bean); (4)
MyService myService = (MyService) bm.getReference(bean, MyService.class, ctx); (5)
1 Retrieving BeanManager thru JNDI
2 retrieving all the beans having MyService in their type and the @Default qualifier
3 apply the ambiguous dependency resolution for the set of beans
4 create a CreationalContext to help contextual instance creation for complex use cases like circularities
5 get the instance

This verbosity is the proof that the BeanManager is and advanced CDI tool allowing very basic operation on CDI echos system. It’s obviously not the best solution if you just want to access an instance.

That’s why, in CDI 1.1 we introduced the abstract CDI class which use Java Service Loader to retrieve a concrete CDI class from the implementation.

CDI<Object> cdi = CDI.current();

CDI gives a faster access to the BeanManager with CDI.getBeanManager() method, but more interestingly, it provides a convenient way to request a contextual instance without using the cumbersome code with BeanManager.

As CDI extends Instance<Object> it naturally provides contextual instance resolution with programmatic lookup.

To make short accessing CDI in your non CDI code provides the same service than having the following injection in CDI code.

@Inject @Any Instance<Object> cdi;

Retrieving an instance becomes as simple as

CDI<Object> cdi = CDI.current();
MyService service =;


CDI 1.1 introduced an other nice feature to help you integrating CDI in non CDI code. The Unmanaged class allows you to apply some CDI operation to a non CDI class.

With it you can call lifecycle callbacks (@Postconstruct and @Predestroy) and perform injection on such class instance. Third party framework developers can then provide their non CDI class including injection point (remember @Inject is not part of CDI spec but AtInject spec) and Unmanaged can be used to get instances of this class.

For instance, imagine this class included in a non CDI archive.

public class NonCDI {

  SomeClass someInstance;

  public void init()  {

  public void cleanUp() {

You can obtain an instance of this class with injection point satisfied with this code

Unmanaged<NonCDI> unmanaged = new Unmanaged(NonCDI.class);
UnmanagedInstance<NonCDI> inst = unmanaged.newInstance();
NonCDI nonCdi = inst.produce().inject().postConstruct().get();

By checking the code in Unmanaged and UnManagedInstance classes you can see how other CDI SPI interfaces are used to provide this feature^

SPI for type meta-model

As all configuration in CDI is based on annotations, we need a mutable meta-model to create or modify existing configuration.

In an other world we could have rely on JDK for type representation and reflection, but as it is read only we had to create our own model in CDI.

type meta

The AnnotatedType interface is main element of this annotation centric type meta-model. other interfaces are abstraction or contained by it.

Defining an AnnotatedType let’s you put all annotations you need on the type, fields, methods or method parameters.

AnnotatedType are mainly used in portable extension They are constructed by the container from existing types.

As you can see, this model has no CDI specific feature, so if a third party developer decide to couple his framework to CDI he can allow his users to play with AnnotatedType to configure his framework

SPI dedicated to CDI meta-model

I already gave a good overview of the interfaces related to Bean meta model in my previous article, so I wont go back into detail on it.

bean meta

Just remember that while this meta-model is mainly used in portable extensions to declare custom beans, it can also be used in your bean to get introspection feature about the current bean, interceptor, decorator or the currently intercepted or decorated bean.

The rest of the CDI meta data SPI interfaces are below:

cdi meta

ObserverMethod and EventMetaData

ObserverMethod interface represent meta data for a given observer method and doesn’t have any usage outside a potable extension. So I’ll deal with in my next article on extensions.

EventMetadata is also related to events but at the opposite logic of EventMetadata, it is only used in usual code and never in an extension. You can inject it in your observer to get information about the event that triggered it.

For instance, you can use it to have stricter approach to observer resolution.

As I wrote in my event post, observer resolution for a given type and qualifiers set, also include an observer for any subclass of the event type and without any qualifier. You could use EventMetadata to restrict this rule by checking effective event type and qualifier like this:

public class MyService {
  private void strictListen(@Observes @Qualified Payload evt, EventMetadata meta) {
    if(meta.getQualifiers().contains(new QualifiedLiteral())
       && meta.getType().equals(Payload.class))
         System.out.println("Do something") (1)
1 this code will be executed only if event type is strictly Payload and its qualifiers contains @Qualified

Producer and InjectionTarget and their factories

Producer and InjectionTarget are also mostly used in extension. But if you took a look to Unmanaged presented above you may have seen that InjectionTarget can be used in usual code to perform some lifecycle operations an injection on a non CDI class.

As Unmanaged doesn’t allow you to perform injection on existing object you can use this code to do it yourself. This can be useful if you want to have object provided by a third party, perform injection in CDI way.

AnnotatedType<MyClass> type = beanManager.createAnnotatedType(MyClass.class);
InjectionTarget<MyClass> injectionTarget = beanManager.getInjectionTargetFactory(MyClass.class).createInjectionTarget(null);
CreationalContext<MyClass> ctx = beanManager.createCreationalContext(null);

MyClass instance = new Myclass;
injectionTarget.inject(instance, ctx);

CDI 1.1 introduced ProducerFactory and InjectionTargetFactory to resolve circular dependency issues when using Producer or InjectionTarget in an extension to create a new kind of Bean. I will detail them in my next post.

InjectionPoint meta-data

Last but not least in this SPI family: the InjectionPoint. This swiss-army knife is as much used in extension than in usual code. But in the later case you can only use it to get information on injection point related to @Dependent scoped bean. It’s the only way to guarantee the injection point uniqueness (i.e. the same @RequestScoped instance can be injected in multiple place). That’s the price to access InjectionPoint power.

Let’s check some nice way to use the InjectionPoint.

Using a qualifier to pass parameter to a producer

As InjectionPoint is used to get info about what’s being injected, info included in a qualifier can be used to decide what to return in a producer

First let’s create a qualifier with non binding member

public @interface HttpParam {
    @Nonbinding public String value(); (1)
1 This qualifier integrates a non binding member, that let us pass information to our producer

Then a producer for a dependent bean that analysis info at his injection point.

@HttpParam("") (1)
@Dependent (2)
String getParamValue(InjectionPoint ip, HttpServletRequest req) { (3)
  return req.getParameter(ip.getAnnotated().getAnnotation(HttpParam.class).value());
1 This producer defines a bean having String in its type set and qualified with our qualifier
2 Remember to use injection point in your bean must be in dependent scope.
3 this producer injects the InjectionPoint meta-data and the built-in HttpServletRequest bean

Finally we can use this producer by injecting the matching bean type and qualifier, with the parameter in the qualifier

String productId;

Analyze requested types a injection point

CDI does a great job to avoid type erasure and guarantee a powerful usage of parameterized types.

In the example below, we have a producer for a generic Map that use different implementations depending on the type of map values requested at the injection point.

class MyMapProducer() {

    <K, V> Map<K, V> produceMap(InjectionPoint ip) {
        if (valueIsNumber(((ParameterizedType) ip.getType()))) (1)
            return new TreeMap<K, V>();
        return new HashMap<K, V>();

    boolean valueIsNumber(ParameterizedType type) { (2)
        Class<?> valueClass = (Class<?>) type.getActualTypeArguments()[1];
        return Number.class.isAssignableFrom(valueClass)
1 this code retrieve the parameterized type defined at the injection point and send it to the test function
2 this test function will check the effective type of the second type prameter (type of the map values) and return true if this type inherit Number

With the code above @Inject Map<String,String> map will use an HashMap under the hood while @Inject Map<String,Integer> map will use a TreeMap. An elegant way to optimize or change behaviour without leakage in business code.


There are lot of features you can imagine to build with InjectionPoint and keep in mind that we only saw a few example in usual code. Imagine what you can do in an extension…​

SPI dedicated to extensions

Let’s end this SPI tour by a cliffhanger.

The following SPI classes are totally dedicated to extension development.

In fact they defined events type for each step in the container lifecycle (mainly the bootstrap part) where the portable extension magic occurs.

spi extensions

Let’s discover this magic in a coming post about extension.

How to recognize different types of beans from quite a long way away

Posted by Antoine Sabot-Durand on Dec 14, 2015 | Comments
the larch

In CDI, Beans are a very centric concept. Yet, for a lot of user, this concept stays fuzzy and requires experiment to achieve an expected result. In this article I’ll try to clarify most of bean related concepts and detail the hidden mechanism behind bean definition and injection.

Bean, contextual instance and typesafe resolution

When most CDI users write

MyBean bean;

they think: "I have injected the MyBean bean having @MyQualifier qualifier".

That’s not correct and it’s important to understand the exact mechanism behind this injection point definition.

Bean vs contextual instances

One of the specific feature in CDI is the fact that all components (qualifiers, beans, producers, etc..) are discovered at deployment time.

It allows the container to raise errors very early (before runtime) and for you to be sure that all injection points you defined will be satisfied and not ambiguous.

While this discovery process is not the topic of this article you should know that all classes packaged with your application will be analyzed at deployment to discover beans (and other components).

At the end of this discovery task, the container had created collections of meta-data for most elements included in CDI SPI. The more centric meta-data created by CDI container is the collection of Bean<T> discovered during deployment. These metadata are the real applications beans and in basic CDI usage you’ll never use them.

So don’t mix beans and the contextual instances (instances of the bean for a given context) you request to the container when adding an injection point in your code.

The content of Bean<T> interface

The Bean interface has two main functions:

  • Providing a "recipe" to create and destroy contextual instances (methods from Contextual<T>)

  • Storing bean metadata obtained from bean definition (methods from BeanAttributes<T>)

Bean Interface hierarchy, yes Interceptor and Decorator are also Beans
Bean Interface hierarchy, yes Interceptor and Decorator are also Beans

The metadata stored in Bean<T> come from the user code defining the bean (type and annotations). If you take a look at BeanAttributes in the above schema, you’ll see that these metadata include a set of types (yes a bean as multiple types) and a set of qualifiers (each bean has at least 2 qualifiers: @Default and @Any). These 2 sets are used in the CDI typesafe resolution mechanism.

Typesafe resolution for Dummies

When you use @Inject in your code, you’re asking the container to look for a certain Bean. The search is done by using info in Bean metadata.

For most injection point this search is done at deployment time to check if each injection point is satisfied and not ambiguous, the only exception is the programmatic lookup (use of Instance<T>). This approach allows the implementation to cache the matching bean for a given injection point.

When the matching Bean is found, the container use its create method to provide you an instance.

This process, called the Typesafe resolution can be simplified like this:

When resolving bean for a given injection point the container considers the set of types and qualifiers of all enabled beans to find the right candidate.

A simplified version of typesafe resolution
A simplified version of typesafe resolution

The actual process is a bit more complex with integration of Alternatives, but the general idea is here.

If the container succeeds in resolving the injection point by finding one and only one eligible bean, the create() method of this bean will be used to provide an instance for it.

So when do we refer to the Bean<T>?

In basic CDI, the answer is "never" (or almost).

Bean<T> will be used 90% of the time in portable extension to create a custom bean or analyse bean metadata.

Since CDI 1.1 you can also use Bean<T> outside extensions.

For the sake of reflection it is now allowed to inject the bean meta-data in a bean class, an interceptor or a decorator, allowing them to have info on metadata of the current bean.

For instance this interceptor use the meta-data of the intercepted bean to avoid issue with proxy creation in the implementation:

public class LoggingInterceptor {

    private Logger logger;

    @Inject @Intercepted (1)
    private Bean<?> intercepted;

    private Object intercept(InvocationContext ic) throws Exception {">> " + intercepted.getBeanClass().getName() + " - " + ic.getMethod().getName()); (2)
        try {
            return ic.proceed();
        } finally {
  "<< " + intercepted.getBeanClass().getName() + " - " + ic.getMethod().getName());
1 @Intercepted is a reserved qualifier to inject the intercepted bean in an interceptor
2 here it is used to retrieve the actual class of the contextual instance not the proxy’s class implementation may have created

Different kinds of CDI beans

Now that we stated the difference between Bean and Bean in stances, it’s time to list all the bean kind we’ve got in CDI and their specific behaviour.

Managed beans

Managed bean are the most obvious kind of bean available in CDI. They are defined by a class declaration.

According to the specification (section 3.1.1 Which Java classes are managed beans?):

A top-level Java class is a managed bean if it meets all of the following conditions:

  • It is not a non-static inner class.

  • It is a concrete class, or is annotated @Decorator.

  • It does not implement javax.enterprise.inject.spi.Extension.

  • It is not annotated @Vetoed or in a package annotated @Vetoed.

  • It has an appropriate constructor - either:

    • the class has a constructor with no parameters, or

    • the class declares a constructor annotated @Inject.

All Java classes that meet these conditions are managed beans and thus no special declaration is required to define a managed bean.

— CDI 1.2 specification

That’s for the general rules, a valid class can also be ignored if the bean discovery mode is set to none or annotated and the class doesn’t have a bean defining annotation.

To sum up, if you’re in the default bean discovery mode (Annotated) your class should follow the condition above and have at least one of the following annotation to become a CDI managed bean:

  • @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.

Another limitation is linked to client proxies. In a lot of occasion (interceptor or decorator, passivation, usage of normal scope, possible circularity), the container may need to provide a contextual instance wrapped in a proxy. For this reason, managed bean classes should be proxyable or the container will raise an exception.

Thus in addition to the above rules the spec also restrictions on managed bean class to support certain services or be in normal scopes.

So, if possible you should avoid the following limitation on your bean class to be sure that they can be proxyable:

  • it should have a non private constructor with parameters,

  • it shouldn’t be final,

  • it shouldn’t have non static final methods.

Bean types of a managed bean

The set of bean types (used during typesafe resolution) for a given managed bean contains:

  • the bean class,

  • evey superclass (including Object),

  • all interface the class implements directly or indirectly.

Keep in mind that @Typed annotation can restrict this set. When it’s used, only the types whose classes are explicitly listed using the value member, together with Object, are bean types of the bean.

Session beans

CDI Session beans are EJB in CDI flavor. If you define a session bean with EJB 3.x client view in a bean archive without @Vetoed annotation on it (or on its package) you’ll have a Session Bean at runtime.

Local stateless, singleton or stateful EJB are automatically treated as CDI session bean: they support injection, CDI scope, interception, decoration and all other CDI services. Remote EJB and MDB cannot be used as CDI beans.

Note the following restriction regarding EJB and CDI scopes:

  • Stateless session beans must belong to the @Dependent scope,

  • Singleton session beans can belong to the @Dependent or @ApplicationScoped scopes,

  • Stateful session beans can belong to any scope

When using EJB in CDI you have the features of both specifications. You can for instance have asynchronous behavior and observer features in one bean.

But keep in mind that CDI implementation doesn’t hack EJB container, it only use it as any EJB client would do.

Thus, if you don’t use @Inject but @EJB to inject a session bean, you’ll obtain a plain EJB in your injection point and not a CDI session bean.

Bean types of a session bean

The set of bean types (used during typesafe resolution) for a given CDI session bean depend on its definition:

If the session has local interfaces, it contains:

  • all local interfaces of the bean,

  • all super interfaces of these local interfaces, and

  • Object class.

If the session bean has a no-interface view, it contains:

  • the bean class, and

  • evey superclass (including Object).

The set can also be restricted with @Typed.


public class ShoppingCart { ... } (1)

public class LoginActionImpl implements LoginAction { ... } (2)

@Singleton (3)
@Startup (4)
public class bootBean {
 MyBean bean;
1 A stateful bean (with no-interface view) defined in @ConversationScoped scope. It has ShoppingCart and Object in its bean types.
2 A stateless bean in @Dependent scope with a view. Usable in EL with name loginAction. It has LoginAction in its bean types.
3 It’s javax.ejb.Singleton defining a singleton session bean.
4 The EJB will be instantiated at startup triggering instantiation of MyBean CDI bean.


Producers are the way to transform standard pojo into CDI bean.

A producer can only be declared in an existing bean through field or method definition.

By adding the @Produces annotation to a field or a non void method you declare a new producer and so a new Bean.

Field or method defining a producer may have any modifier or even be static.

Producers behave like standard managed bean:

  • they have qualifiers,

  • they have scope,

  • they can inject other beans: parameters in producer method are injection points that the container will satisfied when it will call the method to produce a contextual instance This injection points are still checked at deployment time.

Yet, producers have limitation compared to managed or session bean as they don’t support interceptors or decorators. You should keep this in mind when creating them as this limitation is not obvious when reading the spec.

If your producer (field or method) can take the null value you must put in in @Dependent scope.

Remember the Bean<T> interface we talked above ? You can see a producer method as a convenient way to define the Bean.create() method, even if it’s a bit more complicated.

So if we can define create() what about destroy()? It’s also available with disposers methods.


A less known feature of producer is the possibility to define a matching disposer method.

A disposer method allows the application to perform customized cleanup of an object returned by a producer method or producer field.

Like producers, disposers methods must be define in a CDI bean, can have any modifier and even be static.

Unlike producer they should have one and only one parameter, called the disposer parameter and annotated with @Disposes. When the container container finds producer method or field, it looks for matching disposer method.

More than one producer can match to one disposer method.

Bean types of a producer

It depends of the type of the producer (field type or method returned type):

  • If it’s an interface, the bean type set will contain the interface all interface it extends (directly or indirectly) and Object.

  • If it’s a primitive or array type, the set will contain the type and Object.

  • If it’s a class, the set will contains the class, every superclass and all interface it implements (directly or indirectly).

Again, @Typed can restrict the bean types of the producer.


public class ProducerBean {

  private List<Integer> mapInt = new ArrayList<>(); (1)

  @Produces @RequestScoped @UserDatabase
  public EntityManager create(EntityManagerFactory emf) { (2)
    return emf.createEntityManager();

  public void close(@Disposes @Any EntityManager em) {  (3)

1 This producer field defines a bean with Bean types List<Integer>, Collection<Integer>, Iterable<Integer> and `Object
2 This producer method defines a EntityManager with @UserDatabase qualifier in @RequestScoped from an EntityManagerFactory bean produced elsewhere.
3 This disposer disposes all produced EntityManager (thanks to @Any qualifier)


Thanks to producer mechanism CDI allows to expose Java EE resources as CDI Bean.

These resources are:

  • persistence context (@PersistenceContext),

  • persistence unit (@PersistenceUnit),

  • remote EJB (@EJB),

  • web service (@WebServiceRef), and

  • generic Java EE resource (@Resource).

To declare a resource bean you only have to declare a producer field in a existing CDI bean

Declaring resources beans
@WebServiceRef(lookup="java:app/service/PaymentService") (1)
PaymentService paymentService;

@EJB(beanname="../their.jar#PaymentService") (2)
PaymentService paymentService;

@PersistenceContext(unitName="CustomerDatabase") (3)
EntityManager customerDatabasePersistenceContext;

@PersistenceUnit(unitName="CustomerDatabase") (4)
EntityManagerFactory customerDatabasePersistenceUnit;

@Resource(lookup="java:global/env/jdbc/CustomerDatasource") (5)
Datasource customerDatabase;
1 producing a webservice from its JNDI name
2 producing a remote EJB from its bean name
3 producing a persistence context from a specific persistence unit with @CustomerDatabase qualifier
4 producing a a specific persistence unit with @CustomerDatabase qualifier
5 producing a Java EE resource from its JNDI name

Of course you can expose the resource in more complex way:

producing an EntityManager with COMMIT flush mode
public class EntityManagerBeanProducer {

  private EntityManager em;

  EntityManager produceCommitEm() {
    return em;

After declaration resources bean can be injected as any other bean.

Bean type of a resource

Resources exposed as bean with producer follow the same rules than producers regarding their type set.

Built-in beans

Beyond beans you can create or expose, CDI provides a lot of built-in beans helping you in your development

First the container should always provide built-in beans with @Default qualifier for the following interfaces:

  • BeanManager in @Dependent scope,to allow injection of BeanManager in an bean,

  • Conversation in @RequestScoped to allow management of the conversation scope.

To allow the use of events and programmatic lookup, the container must also provide built-in beans for with:

  • Event<X> in its set of bean types, for every Java type X that does not contain a type variable,

  • every event qualifier type in its set of qualifier types,

  • scope @Dependent,

  • no bean name.

For programmatic lookup the container must provide a built-in bean with:

  • Instance<X> and Provider<X> for every legal bean type X in its set of bean types,

  • every qualifier type in its set of qualifier types,

  • scope @Dependent,

  • no bean name.

A Java EE or embeddable EJB container must provide the following built-in beans, all of which have qualifier @Default:

  • a bean with bean type javax.transaction.UserTransaction, allowing injection of a reference to the JTA UserTransaction, and

  • a bean with bean type, allowing injection of a Principal representing the current caller identity.

A servlet container must provide the following built-in beans, all of which have qualifier @Default:

  • a bean with bean type javax.servlet.http.HttpServletRequest, allowing injection of a reference to the HttpServletRequest

  • a bean with bean type javax.servlet.http.HttpSession, allowing injection of a reference to the HttpSession,

  • a bean with bean type javax.servlet.ServletContext, allowing injection of a reference to the `ServletContext

Finally to allow introspection of dependency injection and AOP, the container must also provide the built-in bean in @Dependent scope for the following interfaces when a an existing bean inject them:

  • InjectionPoint with @Default qualifier to get information about the injection point of a @Dependent bean,

  • Bean<T> with @Default qualifier to inject in a Bean having T in its typeset,

  • Bean<T> with @Intercepted or @Decorated qualifier to inject in an interceptor or decorator applied on Interceptor and Decorator for a bean having T in its typeset.

Check the spec on bean metadata to get all the restriction regarding Bean injection.

Custom beans

CDI gives you even more with Custom beans. Thanks to portable extension you can add your own kind bean allowing you to hook on the instantiation, injection and destruction of the instances.

You could for instance look in a registry to check for a given instance instead of instantiating the object.

I’ll show you on a coming post how to create such a bean in a portable extension.


As you see there are a lot of things happening behind the @Inject scene. Understanding them will help you to make a better use of CDI and give you a clearer entry point to Portable extension

You think you know everything about CDI events… Think again!

Posted by Antoine Sabot-Durand on Jun 10, 2014 | Comments
Event bus
Event Bus may surprise you

CDI events are one of the shiniest feature in the CDI specification. They are a easy to understand and use and are a straight forward implementation of the Observer Design Pattern. To sum up they add more decoupling to the Dependency Injection by allowing notification of unknown target at development time (great to develop framework). Yet, documentation about event is often misleading and contains inaccurate information, probably due to the fact that the specification was wrong before we corrected it for CDI 1.2 release ;). This post is the opportunity to update or clarify your knowledge about how events work in CDI 1.0 and 1.1+ and what could come in CDI 2.0. If you want to “play” with event you can checkout my Github project EventsTest to use it as a sandbox.

If you are familiar with events you can directly go to the more advanced or less know features

Back to the basics

Before going further, let’s introduce basic concepts around CDI events.

What’s an event?

CDI events are defined by 2 things :

  • A java object (the event object)

  • A set of qualifiers (annotations having the meta annotation @Qualifier) The event Object could be of any Java type and don’t have to be CDI related (try to avoid using bean instance as event object, it’s confusing and if the bean scope is not @Dependent could bring issues related to bean lifecycle). Qualifiers are the same used to define CDI Bean or injection point. They can have members or not. And their members value are part of the qualifier definition or not (if they have the @NonBinding annotation).

How to fire an event?

The most universal way to fire an event is to use the BeanManager.fireEvent(Object event,Annotation…​ qualifiers) method. BeanManger is directly accessible in CDI bean by injecting it:

BeanManager beanManager;

public void doSomething() {
  beanManager.fireEvent(new Payload());

Outside CDI you can alway retrieve it by JNDI (by looking up for “java:comp/BeanManager” name)or more easily in CDI 1.1+ via CDI class:

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

public void doSomething() {
  beanManager.fireEvent(new Payload());

In CDI bean, it is more common and natural to use the Event<T> interface to get possibility to fire an event like this:

Event<Payload> payloadEvent;

public void doSomething() { Payload());

The Event<T> interface is an helper to fire event whose type is totally CDI agnostic and thus doesn’t include a way of being fired. To make a gun fire analogy, In the previous example, see payloadEvent as the bullet case while the bullet is the instance of Payload you gave as parameter of the fire() method.

Observing events

To observe an event you’ll have to add an observer method in an enable bean of your application. An observer method is a method whose first parameter has the @Observes annotation. The type of the parameter with @Observes will be used to resolve target observer when an event is fired as we’ll see later. So:

public void listenToPayload(@Observes Payload event) {

will be triggered (if the method is in an active bean) for all events whose type are Payload or a super type of Payload. Off course qualifier may be added to the observer to restrict event triggering:

public void listenToPayload(@Observes @Qualified Payload event) {

The observers resolution occurs at runtime when an event is fired. All the observers that match the event will be triggered by the CDI container. Note that the observer method may have other beans as parameters. They will be injected by the container before calling the method :

public void listenToPayload(@Observes Payload event, PayloadService service) {

Features you may have missed regarding CDI events

The following CDI events feature are less known or badly documented.

No type erasure for event type

It’s not an hidden feature but more something implicit in CDI than can be missed. As CDI is a type centric specification (I always sigh when I see and injection point with a @Name qualifier), it does a better job than standard Java regarding parameterized type.

For instance take these 2 observer methods:

public void processNumberList(@Observes List<Number> event) {

public void processIntegerList(@Observes List<Integer> event) {

The container will make the distinction between both when resolving observer depending of the parameterized type of the event. And in CDI 1.1+ (wildcards are not allowed in observer event parameter in CDI 1.0) if you declare the following observers :

public void processIntegerList(@Observes List<? super Integer> event) {

public void processNumberList(@Observes List<? extends Number> event) {

Both will be called if your event type is List<Integer> or List<Number>. Although the first observer will fit for add elements to the list while the second will be used to fetch elements from the list.

Remember that if wildcards are allowed in observer in CDI 1.1+ if they aren’t in Event injection point.

Qualifiers don’t work with event as they work with beans

That’s an important point that was very badly explained in the spec before CDI 1.2. Developers often assume that Event<> and Instance<> have quite similar way of functioning regarding qualifiers, that’s a big mistake. But let’s start with the most important here :

An observer matches an event if its type is in the event types set and if the observer has a subset of the qualifier of the event.

Better check this with a piece of code

 * Qualifier with binding member
public @interface Qualified {
    String value() default "";

public class EventTestService {

    Event<Payload> payLoadEvent;

    public void fireEvent() { Payload());

    public void processUnqualifiedPayload(@Observes Payload event) {}

    public void processQualifiedPayload(@Observes @Qualified("strong") Payload event) {}

    public void processUnqualifiedObject(@Observes Object event) {}

    public void processQualifiedObject(@Observes @Qualified("strong") Object event) {}


Yes, all the 4 declared observers will be called by the container when the event is fired. Useful to know that ;).

So @Any qualifier is totally useless on events or observers

The spec requires that all created events should have the @Any automatically added, but as we just saw @Any has the same behavior in event that @Default qualifier (no qualifier), so prefer using no qualifier instead of using @Any, it’ll be less confusing.

Event<> is here to build events not filter them

Again Event looks like Instance but is very different. While Instance is a tool to lookup for beans, Event is a tool to build an event from an object and qualifiers. So keep in mind that when you use qualifiers) you are adding qualifier to the event you’ll be firing. For instance :

public class EventTestService {

    Event<Payload> payLoadEvent;

    public void fireEvent() { QualifiedLiteral()).fire(new Payload());

public class QualifiedLiteral extends AnnotationLiteral<Qualified> implements Qualified {

    private String value="";

    public QualifiedLiteral(String value) {
        this.value = value;

    public QualifiedLiteral() {

    public String value() {
        return value;

will add the @Qualified qualifier to the event before firing it. So the final event will have @MyQualifier @Qualified("") qualifiers.

Advanced Event Features

Conditional Observer methods

As we saw, observer methods have to be in a bean to be registered by the container. If the bean containing the observer has a different scope than @Dependent we may want to control if the call to the observer should trigger bean instantiation. You can do that with the receive member of @Observes annotation which can take the enum values javax.enterprise.event.Reception.ALWAYS (by default) or javax.enterprise.event.Reception.IF_EXISTS.

public class EventTestService {

    // will always be called (bean my be instantiated for this call)
    public void processQualifiedPayload(@Observes(receive=ALWAYS) Type1 event) {}

    // will be called only if the bean already exists in Request scope
    public void processUnqualifiedPayload(@Observes(receive=IF_EXISTS) Type2 event) {}


Remember that IF_EXISTS cannot be used in a bean having @Dependent scope since the bean cannot exists before observer is called. If you do the mistake the container will remember you that at startup.

Transactional observer methods

Transactional observer methods are observer methods which receive event notifications during the before or after completion phase of the transaction in which the event was fired. If no transaction is in progress when the event is fired, they are notified at the same time as other observers.

  • A before completion observer method is called during the before completion phase of the transaction.

  • An after completion observer method is called during the after completion phase of the transaction.

  • An after success observer method is called during the after completion phase of the transaction, only when the transaction completes successfully.

  • An after failure observer method is called during the after completion phase of the transaction, only when the transaction fails.

You can specify the transaction phase of the observer call with the during member of the @Observes annotation. The enumeration javax.enterprise.event.TransactionPhase identifies the kind of transactional observer method the enum values are:


public class EventTestService {

    // is called when the event is fired
    public void processCustomerUpdateRequest(@Observes(during=IN_PROGRESS) @Updated customer cust) {}

    // is called by the same event fired than previous observer but only after the trnsaction complete successufully
    public void processCustomerUpdated(@Observes(during=AFTER_SUCCESS) @Updated customer cust) {}


Note that the transaction observer mechanism is the only way to differ and order some observer right now.

Built-in events linked to scope lifecycle (CDI 1.1+)

Since CDI 1.1, the container fire events when context are created and destroyed, thanks to the provided @Intialized and @Destroyed qualifiers. If your application is deployed in a servlet container, the event payload correspond to the servlet scope object corresponding to the initialized or destroyed CDI scope. Otherwise payload will be java.lang.object You can observe these event in your application like this (if it’s deployed in a servlet container) :

public void processApplicationScopedInit(@Observes @Initialized(ApplicationScoped.class) ServletContext payload) {}

public void processApplicationScopedDestroyed(@Observes @Destroyed(ApplicationScoped.class) ServletContext payload) {}

public void processSessionScopedInit(@Observes @Initialized(SessionScoped.class) HttpSession payload) {}

public void processSessionScopedDestroyed(@Observes @Destroyed(SessionScoped.class) HttpSession payload) {}

public void processRequestScopedInit(@Observes @Initialized(RequestScoped.class) ServletRequest payload) {}

public void processRequestScopedDestroyed(@Observes @Destroyed(RequestScoped.class) ServletRequest payload) {}

public void processConversationScopedInit(@Observes @Initialized(ConversationScoped.class) ServletRequest payload) {}

public void processConversationScopedDestroyed(@Observes @Destroyed(ConversationScoped.class) ServletRequest payload) {}

Specification encourage third party extension to do the same for custom context.

Events Metadata (CDI 1.1+)

Version 1.1 of the spec introduced EventMetadata interface. It allows an observer to get all the metadata about an event. You get the EventMetadata by adding it to the observer parameters :

public void processPayload(@Observes Payload event, EventMetadata meta) {}

The EventMetadata contains the following methods:

  • getQualifiers() returns the set of qualifiers with which the event was fired.

  • getInjectionPoint() returns the InjectionPoint from which this event payload was fired, or null if it was fired from BeanManager.fireEvent(…).

  • getType() returns the type representing runtime class of the event object with type variables resolved.

This bring a solution to add more fine-grained filtering on observer execution depending on actual metadata of the triggered event

Events limitation

Right now, CDI events have two big limitation out of the box

Events are only synchronous

Out of the box events are synchronous: method firing an event has to wait the end of all observers invocation before executing instruction after event firing. So no fire and forget option and off course no callback approach. The obvious solution if you need asynchronous event approach is to use an EJB method as an observer and annotate it @Asynchronous. Other options exists but you need to create a CDI portable extension and play with threads. I’ll try to explore that in a future post.

Observers have no orders

Yes, there’s no out of the box solution to guarantee order of observers execution. The only tiny exception is using transaction phase to do so but it’s very limited. Perhaps a CDI extension could help us here again. I’ll try to explore this approach in a future post.

Pattern and tips with events

Putting all the knowledge we have now on event and other CDI stuff we can figure out some interesting pattern for our developement.

The plugin Pattern

We saw that CDI event data is totally free. You can choose any object (again avoid no dependent bean) to fire an event and this object will be received as a playlod by each observer matching the event type and qualifier. An other interesting fact is that this payload is mutable and can be modified by its observers. Following this idea, observers can become a way to enrich a given object with new data. We can use this approach to seamlessly enhance content by adding a CDI archive to an existing application.

The catch them all pattern

Need to observe all fired event and have their info (for logging purpose for instance), you only have to observe Object.

public void processPayload(@Observes Object event, EventMetadata meta) {}

EventMetadata will even help you to know in which bean the event was fired. A nice way to build a bridge with a messaging service (did I say JMS? ;) )

Don’t forget Interceptors and Decorators

While it’s forbidden to declare observer in decorators or interceptors, you can still fire event from them. So they can be used to enhance existing bean and add event triggering to them without touching their code. A nice way to add event notification only when needed.

Future for CDI events

We have a lot of idea in CDI 2.0 regarding event enhancement. Off course adding observer priority and asynchronous treatment are on the top of the list. On asynchronous event we could even think of adding callback method support based on java.lang.invoke package. More ambitious ideas are floating around like giving a range to events making them cross the War or Ear barrer and spread across the server or the cluster. That could lead us to provide an event bus at the server level and help java EE to adopt new application architectures in the future EE versions.

Forward CDI 2.0

Posted by Antoine Sabot-Durand on Mar 15, 2014 | Comments

back to the future CDI is probably one of most overlooked specification in Java EE, yet when version 1.0 was released 4 years ago it was presented as “Java EE extension point”. Technically it’s the case, but for all kind of reason some JSR didn’t adopt CDI totally to provide a more consistent experience in Java EE. Today the IT world is moving fast and after long years of heavy memory and process solution we’re going back to resource optimization with mobile or embedded platform. As CDI can leave outside Java EE, it could play an interesting role in this new approach. But before that it should evolve to be ready for this new challenge (and continue to pursue its growing role in Java EE as well) In this post I’ll try to share my ideas on how CDI should evolve to meet it future rendez-vous. So I’ll start by exposing the new feature I’d like to see in CDI before exploring a more modular architecture for the spec to make it scalable from Raspberry Pi to Huge cluster solutions.

Disclaimer : Since I’ll be leading CDI 2.0 specification (with Pete Muir) it’s important to stress that this post is not an official announcement about the content of the CDI 2.0 specification. It’s only my thought and doesn’t engage CDI Expert Group or Red Hat.

New features I’d like to have

Some of these features are already in the Expert Group pipeline, some were deferred during CDI 1.1 for CDI 2.0, some are standardisation of third party development (mainly Apache Deltaspike) and some are totally new. Anyway, most of these point are important to help third party project or JSR to get the best of CDI.

Java SE Bootstrapping

I don’t need to insist on this point. Today each implementation provide a way to bootstrap CDI in Java SE or in a poor server (Servlet only) environnement. Apache Deltaspike has a generic solution to do it. So it’s time that the CDI spec integrates this to be officially available in Java SE.

Container hot swap

Strong typed injection is great, but CDI is too strict on this in my opinion. To support dynamic JVM language, we should be able to trigger a BeanManager restart with runtime added bean. this could be done for instance by providing API for bootstrapping a new CDI container with augmented content. If the boot went well have more step to duplicate status and existing instance in the new container and garbage the old one. In case of error we could keep the existing BeanManager. A costly but very useful feature for advanced tools or app that could provide specific enhancement system (CMS, e-commerce platform, etc…).

CDI lite

As said in my introduction, there’s a shared wish to bring CDI to embedded devices like Raspberry pi, Arduino, Lego Mindstorms or Android. Today the massive uses of proxies in implementations prevent us to go in that direction.

Java Proxies were very useful in the 2000’s, but now they begin to be old fashioned and brings a lot of problem (huge stack trace, JVM optimization, High resource consumption, etc…). Right now CDI spec take for granted that proxies will be used in implementations.

For this reason, it could be a good solution to provide a subset of CDI specification with less magic and less weight. Let’s call it “CDI Lite” (like EJB Lite that were introduced in Java EE 6). This CDI subset would keep all the DI stuff but would probably get rid of all the Context part as well as Interceptor and Decorator.

But there are others tracks that could be explored to make CDI lighter without removing some of its features.

Bye bye Proxy, hello Annotation Processing and InvokeDynamic

This other way is to find solution to replace proxies by something else in CDI implementations. Right now we have two candidates :

  • Annotation Processing : process Annotation at compile time to produce the “magic” injection/injected/decorated code in a static way like it’s done in Dagger.

  • InvokeDynamic : Runtime linking could provide a proxy-like behavior with less drawbacks and probably more performances. Regarding this second approach I started to do some researches and hope provide a proof of concept soon.

XML config file

It’s time to provide this feature in the spec. There use to be extensions out there that provide this feature, but this is a core feature allowing bean registering and annotation overloading at deploy time and it should be in the spec. If CDI could become more and more present in the other spec, it could also be the beginning of a universal Java EE config file format !

Today, some framework like Apache Camel cannot use CDI because there is no config solution. Providing a solution on that point would ease CDI adoption.

Asynchronous event / action

At the vert.x and node.js era we definitely should support asynchronous treatment (and let’s dream : call back). This could be done By using concurrency spec. We would provide a way to support asynchronous call without using EJB and asynchronous event by adding a boolean asynchronous field in @Observes and, optionally, a handle on a callback

Support of @Startup

An easy feature to add : provide a way to have a CDI bean automatically instantiated after the initialization phase like we already have in EJB.

It’s a very common request by developers and it’s not very hard to provide.

Portable Extension SPI promotion / usage simplification

CDI Lifecycle
CDI 1.1 container initialization and Lifecycle

Portable Extension is, in my opinion, the best feature in CDI. Off course IoC, events or context management are great but they weren’t new when introduced in CDI 1.0.

Portable extension is a complete CDI innovation, that added to Java EE DNA the possibility to be naturally extended without using proprietary tricks.

In my opinion it’s a pity that Portable Extension were not more promoted (CDI acronym doesn’t include any idea of their existence for instance) and were placed at the end of our specification document since a lot of projects or other specification could benefit from it.

My analyze is that this lack of communication is linked to the bunch of more or less complexe concepts (like the container initialization events shown in the right side schema) to understand before being able to deep dive into extension development. We should probably provide a higher simplified layer to get started with basic task on extension. Don’t misunderstand me, the existing mechanism is great and should be kept (with probably some enhancement) but we should provide helpers to ease extension creation. These helper could be :

  • Standardization of Deltaspike AnnotatedTypeBuilder and BeanBuilder to ease new Beans creation

  • Helpers on introspection tools regarding types or annotation manipulation

  • Easier way to create new scopes or extend existing ones. We encourage other spec to extend lifecycle of existing scopes (like @RequestScoped for Websocket) but it’s nearly impossible to do it without going at the implementation level.

We should also bring a special attention to the first events (until AfterTypeDiscovery) in this initialization process, since they are CDI agnostic dealing only with type and annotation metadata modification. These could become part of a future Java EE configuration system.

Ordering event execution

So in CDI 1.1 decorator and interceptor are ordered thanks to @Priority. What about ordering events ? Using @Priority on @Observes doesn’t seem a good idea since this annotation comes from the interceptor package, but we could add an int priority field in @Observes.

No more segregation for Producers and Custom beans

Why produced bean or custom bean should be CDI second class citizen? I want to be able to decorate or use interceptor on my produced beans or at least have APIs that allow me to add this features to my produced beans.

Event scoping from package to server wide

Having the CDI event bus at a higher level in Java EE would allow scoping our event. Soone could decide if the event should stay in the current application, be restricted to the current module (in an EAR) even the current package or on the other side be broadcasted to all app listening to it.

Transient injection

When injecting dependent bean in a longer living bean, this injection is done once when the longer bean is instantiated. There are use cases (I’ve got one in Agorava) where I want my dependent bean to be re-injected each times it’s accessed. Today I have to write :

@Inject Instance<MyBean> myBeanInstances;
public Mybean getMyBean() { return myBeanInstances.get(); }

Tomorrow I’d like to write this :

@Inject @Transient MyBean myBean;

It’s mainly syntaxic sugar but make the code more easy to write and readable. We probably could find other example here of code simplification.

Have a more fluent programmatic lookup

The Instance<T> interface and the programmatic lookup are incredibly useful, but it could be very cumbersome to use especially when we have to deal with Qualifiers.

This could be eased by providing tools to generate qualifier literals with Java 8 Type Annotations for instance. And why not a query DSL ?

myBeanInstance.restrictedTo(BeanImp.class).withQualifier(new @MyQualifier("Binding") AnnotationLiteral<>(), new @MyOtherQualifier AnnotationLiteral<>()).select();

Wouldn’t it be more user friendly ?

Monitoring facility

Remember the great debug page in Seam 2 ? I’d like to have the same things or tools to easily build the same feature to monitor my beans and my scope. CDI does a lot of Magic and it could be nice to have tools to see all its trick and the cost of beans, context and other interceptor we deployed

Give me more modularity : a new architecture for CDI (and Java EE ?)

CDI Next Architecture

A lot of JSR complained that CDI spec is too monolithic and that implementations are too heavy comparing to theirs (they don’t want to depend on something bigger). This and the lack of standard Java SE bootstrapping, are probably the 2 mains objection to go for a deep CDI integration in some spec. So we should provide a more modular approach while keeping the possibility to gather all the modules and have a consistent stack that we could use outside Java EE. In my ideal world the different JSR / Modules would be :


This module store all the beans defined in the application. Providing as a standalone module brings the following features :

  • Provides a minimum api/impl for a client app that rely on JNDI to get Beans

  • Provides the possibility to add plugins to the container to support new kind of components (Servlet, JPA Entity, Guice or Spring beans for instance)

  • Prepare the CDI container to be the future universal Java EE container that we’re waiting for

Event bus

Events and observer pattern are great features of CDI spec. But they would be more useful if spec could use them without having to depend on all CDI.

We could imagine a new Java EE specification or a CDI module based on CDI event API to provide Java EE wide eventing model. We could imagine an API only relying on half a dozen classes (more if we add asynchronous treatment, ordering and event scoping) hat would do the Job.

Component Scanning & Extension engine

Today each specification does class scanning at boot time. In general the app server provides a way to group this scanning process in a proprietary way. By standardizing the scanning phase events and the meta-data manipulated during this scanning phase we could provide a consistent experience and a standard way to extend Java EE. CDI already provides most of this feature with its initialization mechanism which allow to “observe” all wished existing classes in deployment and modify meta-data of these classes (i.e. annotations) .

Imagine what you could do if the ProcessAnnotatedType event could be catch at the server level and allow you to put a “veto” on a given servlet or on a group of JPA entities? This feature lead us on the single container and the single configuration file path. A feature dreamt by a lot of developers.

Basic DI

This module would include all API related to simple injection (only pseudo-scope). So all @Inject, @Qualifier, Instance<T>, @Producer, InjectionPoint and other Reflection stuff will be gathered in a light API. Probably what I called “CDI lite” in my previous part.

Context Management

Context is a nice feature of CDI but as everybody don’t need it, it should be put in a optional API package. This part will deal with all the normal scope context and complex life cycles.

Interceptor & Decorator

Today interceptors already have their own JSR. Adding decorator to the JSR would complete the interceptor JSR.

Conclusion : CDI needs you!

So, here’s my personal CDI wish list. You probably have yours (we collected your 3 CDI 2 wishes in december / january, and we intend to use them. If you didn’t send them, feel free to add them in comment of this article). I don’t know if all these point are good ideas (just read the comment to make your opinion). I don’t know if they are all doable (probably not). What I know is that we’ll need all help we can have to work on the future CDI 2.0. So if you want to be part of this adventure, stay tuned on CDI official website, @cdispec twitter account (or mine) and this blog and give us your feedback on CDI ML or CDI IRC channel (#jsr346 on freenode). The coming months will be decisive regarding CDI (and Java EE) future.