Contexts & Dependency Injection for Java

Meet CDI at Java One 2015

Posted by Antoine Sabot-Durand on Oct 23, 2015 | Comments

During Java One 2015, a lot of CDI related talks and event will happen. find most of them in this post

In this agenda you’ll find most of CDI related talk to help you prepare your schedule

Focus on EG talks

If you want to have the best of CDI overview in Java One, don’t miss these talks:

  • CDI 2.0: Whats in the Works? (monday 12:30, Cyril Magnin I): to learn about coming features in CDI 2.0

  • Apache DeltaSpike, the CDI Toolbox (monday 2:30, Cyril Magnin I): Discover Apache DeltaSpike, the heart of CDI Ecosystem

  • Advanced CDI in live coding (tuesday 8:30, Cyril Magnin II/II): learn the power of CDI portable extension to integrate your framework in CDI programming model

I’ll be available for you questions

You’ll find me at the Hackergarten Tuesday afternoon and wednesday morning to help you on CDI, answer your question or discuss the spec. You can even pass by just to say Hello aor bring me a beer, coffee ;).

Have a nice Java One Week.

Learn CDI spec with our TCK

Posted by Antoine Sabot-Durand on Oct 15, 2015 | Comments

Beyond being one of the few open source TCK around, CDI TCK is one of the easiest to get started with.

Now that we have released a new version of spec doc embedding TCK test, it’s easier than ever.

Learn what we did and how to use it.

CDI TCK for the dummies

TCK stands for Technology Compatibility Kit. It’s one of the 3 part a JSR expert group has to release (2 others being the spec and the Reference Implementation).

A TCK is a collection of tests that actively define the spec. It’s the tool that is used to determine if an implementation is a CDI implementation or not. So this piece of code is the most important and the hardest to develop and maintain. Ok, RI could seem more important, but it’s under the spotlight and is nothing without the TCK.

To make short, TCK is the code that makes CDI a specification and thus a standard.

The great guy behind our TCK is Tomas Remes and he doing an awesome job pointing holes or unclear statements in spec text or refactoring all the TCK after CDI split in 2.0-EDR1.

If you want to learn more about the TCK I suggest that you check our dedicated page.

TCK is more than what it seems

The TCK role is not restricted to the specification mold, it can also be a great way to learn the spec by code. To crown that, thanks to Arquillian, CDI TCK is very easy to understand and very expressive.

But jumping from specification to test can be a bit complicated and this exercise can discourage many of our user.

That’s why, a few months ago, we started to think about a solution to create links from the spec text to the TCK.

It seemed quite doable since the reverse link has always existed: each since TCK tests have meta data about the spec section it refers.

So, Tomas made the required upgrade to the TCK and developed a script to add tests to the spec.

Meet Spec doc with TCK assertion

Don’t worry the original specifications docs stay unchanged, we only released a new flavor for them on our download page.

Due to normalization constraint (rules duplication avoidance) we have on the spec, some statement could seem confusing when reading them.

Let’s take, for instance, the first statement of section 3.15 Unproxyable bean types:

The container uses proxies to provide certain functionality. Certain legal bean types cannot be proxied by the container:

  • classes which don’t have a non-private constructor with no parameters,

Yeah a triple negation…​

You could take the next minute to figure out the exact meaning of the sentence or you could click on the "Show TCK assertions" link and check the two tests related to this section to see the cases where this rules make the deployment fails.

Learn, test and challenge

Now that you have this nice tool in your hand, TCK will be your CDI Lab, and perhaps, you’ll come back with corner use cases not covered or new challenges for the TCK.

Go and learn!

CDI 2.0 Second Face to face meeting feedback

Posted by Antoine Sabot-Durand on Sep 29, 2015 | Comments

Last week we had our second CDI 2.0 Face to Face meeting in Paris (France). This is a summary of the point discussed and leads we’d like to follow. Of course each point we’ll lead to a proposal later and discussed on the mailing list.


CDI 2.0 is still planned for 1st half 2016. We’ll focus on new feature and SE support for this release.

CDI 2.1 should start after 2.0 release and focus Java EE 8 specific enhancement. We’ll probably focus a bit more on modularity since Java 9 will be around the corner giving us a better visibility of how anticipate its new module approach. Content of 2.1 will be defined in the coming weeks

CDI SE review

CDI bootstrap on Java SE is one of the feature released in our first early draft. The Java SE support needed extra work to be complete and we wanted to review the boot api included to see how it could be enhanced.

bootstrap API

We’d like to review the proposed bootstrap API to make it a bit richer and have the boot process in a specific class. The idea is to get inspiration from the new Weld Se bootstrap with a builder pattern (see Weld and WeldContainer classes) and the possibility to explicitly choose the implementation if multiple impl should be in classpath.

Context control

This feature seemed a bit risky to specify. We’d preferred an approach based on existing built-in scope: RequestScoped and an interceptor activating it for a given invocation and unactivating it just after . something like this:

public void doSomethigWithRequestScopedBeans() {

This could give users the possibility to start and stop a context without explicitly adding these methods in the SPI We also discussed the possibility to have a Conversation-like context activated thru a built-in scope.

Bean discovery mode

The new bootstrap api should prevent us to specify a new bean discovery mode since the builder api will contains a mean to deactivate bean discovery and create a synthetic bean archive by adding class and packages of beans.

Async event review

There was discussion about exceptions handling and the issues raised from mixing sync and async observers. So the leads we’d like to follow are the following

  • stop calling sync observer from fireAsync() (fire() is for @Observes and fireAsync() is for @ObservesAsync)

  • Remove FireAsyncException in favor of CompletionException since an exception during async events pipeline execution is noting more than that.

To sum it up:

Table 1. async and sync events rules
Event method @Observes notified @ObservesAsync notified


yes, in the same thread




yes, in a different thread

CDI Lite

As you know, CDI lite is one of the expected features for CDI 2.0. Yet, adding it with the SE / EE split for 2.0 could bring a lot of glitches and could reveal itself a catastrophe without speaking of specific impl and TCK for it.

That’s why we choose to add it in the annexe of the spec as a proposal for a next CDI version. Implementation will be allowed to create their CDI lite version based on this subset of CDI features:

  • JSR 330 with CDI type resolution rules

  • CDI qualifiers usage

  • Producers and disposers

  • Programmatic lookup

  • @Singleton and @Dependent pseudo-scopes support

  • SE bootstrap

We choose not to include events and spi to keep the impl lite. Of course this could be change during our discussion.

AOP on producer and custom beans

The goal was to propose a solution to apply Interceptors and Decorators on produced beans or custom beans. For producers we also have the problem of applying interceptor binding only on some method and not on the whole class. We looked for a solution that could be used in both case and that was more an "advanced users" approach than an out of box one.

The idea is to provide a class or a built-in bean to help produced bean instances using AnnotatedType to allow override of annotation on instance class. This suppose the addition of AnnotatedTypeBuilder to the SPI to ease the use of building a synthetic AnnotatedType. This would follow the same idea than the Unmanaged class which provide a way to inject bean in a non bean (non managed) class.

That would give something like:

public class MyAdvancedProducerBean {

    public BeanInstanceBuilder<MyClass> bib = new BeanInstanceBuilder<>();

    public MyClass produceTransactionalMyClass() {

        AnnotatedTypeBuilder<MyClass> atb = new AnnotatedTypeBuilder<>()
            , new TransactionalLiteral());

        return bib.readFromType(
            .build(); //instance of the bean with requested interceptors / decorators

    public void disposeMyClass (@Disposes Myclass td) {



A similar mechanism could be used in the create() method of custom beans.


Of course, all these points will be described in more detail in coming proposal documents. You’ll only find here general ideas of what we like to propose.

We also worked on other points in Jira for clarification or fix. This will go to the mailing list.

This post will be updated with new information or clarification if needed.

CDI 2.0 Early Draft Review 1 released

Posted by Antoine Sabot-Durand on Jul 03, 2015 | Comments

After eight months of work, the CDI 2.0 expert group is pleased to release this first draft of CDI 2.0 specification for community review. This draft contains important and long awaited features that will change CDI as we know it.

But these features are still proposals and we really need your feedback to know if the way we specified them fits your needs. Let’s check what’s on the menu.

CDI runs now in Java SE

One of the oldest request was the support of Java SE in CDI. Since the beginning the two main implementations (JBoss Weld and Apache OpenWebBeans) proposed proprietary solutions to use CDI in Java SE.

Then, Apache DeltaSpike came in and provided an absract solution to boot either implementations, but this wasn’t never standardized at spec level, until now…​

Why this important?

So, if implementation and a third party project already provide this Java SE support, what’s the big deal to have it at spec level? The answer is "increase adoption by other specifications".

A lot of Java EE specification provide a Java SE support (like JPA or JAX-RS). Since CDI doesn’t provide this support as well, they can’t rely totally on it since it is not available in Java SE. So, the side effect of this new Java SE support will be a better CDI integration in Java EE. If we add to this a broader adoption by third parties framework, we see that the benefits for CDI and its users goes far beyond the simple feature.

Preparing Java SE support (API split)

Adding such a straight forward feature to CDI seems quite easy on paper but, trust me, it wasn’t.

If you check the current 1.2 specification, you’ll see that EJB is everywhere in the spec. You also have reference to JSF, servlet or Expression Language all accross the document.

So the first work was to split the spec to put he Java EE specific feature in a dedicated part to have all CDI core feature (no tie to other spec) in its own part. This specification has now 3 parts plus an introduction as explain in the foreword section.

This work was done as carefully as possible to avoid destroying, duplicating or modifying rules, yet, your double check here is most welcome to be sure that we didn’t forget something in the rewriting.

Yes it’s rather long work to read (or re-read) the whole specification but it’s also the ocasion to see it with a fresh eye with this new organisation. You migh want grab the pdf version (whose look has been updated) of the spec to go through it.

Booting CDI in Java SE

After all this work (invisible for end users), we introduced the Java SE support by adding a bootstrap API for Java SE. The solution make use of already existing CDIProvider interface and CDI class.

Code for booting CDI in Java SE looks like this:

public static void main(String... args) {
    try(CDI<Object> cdi = CDI.getCDIProvider().initialize()) {
        // start the container, retrieve a bean and do work with it
        MyBean myBean =;
    // shuts down automatically after the try with resources block.

Go check the Bootstrapping a CDI container in Java SE chapter in the specification and tell us what do you think.

Still work to do

Java SE support needs more work and we are still working on the feature. The two main aspect are:

Again, your feedback and ideas are most welcome to help us for these part specification.

Ordering event observers

One of the oldest requested feature for CDI was resolved in this EDR : observer ordering.

The feature was simply design by using @Priority annotation (from commons annotation) and will be used like this:

void afterLogin(@Observes @Priority(APPLICATION) LoggedInEvent event) { ... }

The use of @Priority was rather obvious since we already use this annotaion for interceptor, decorator or alternatives activation and ordering. The only issue here is that the annotation only targets types right now. We asked for a review of JSR-250 to add parameter as accepted target for @Priority.

Check the section dealing with observer ordering to have all the details.

Asynchronous events

Another important feature requested by many of you. Introducing Asynchronous event wasn’t an easy thing, because we needed to keep backward compatibilty with existing events. We also wanted to leverage new asynchronous API in Java 8 to provide the most up to date approach in the spec.

The solution we choose was to introduce @ObservesAsync and add methods fireAsync() in the Event interface. So the exisitng observer (defined with @Observes) will stay synhcronous and new observer defined by @ObservesAsync will be called asynchronously if the event was triggered with fireAsync() (and won’t be called from a classical fire()).

So asynchronous event usage will look like this:

@Inject Event<LoggedInEvent> loggedInEvent;

public void login() {
    loggedInEvent.fireAsync( new LoggedInEvent(user) );


public void asyncAfterLogin(@ObservesAsync LoggedInEvent event) { ... }

The best is to re-read all the event chapter in the spec to get the details.

Why this double activation is needed?

For the producer (fire()) side it’s rather obvious : we cannot magically change all synchronous event call to async. We need an handle on the work in progress (so a new method signature with CompletionStage), the payload mutation mechanism would break as all transactional events. So there’s no debate on fireAsync().

On the observer side, the reason is for backward compatibility. CDI events are a great way to cross boundaries of our own code and activate unknown code at runtime in another module of the app (i.e. another jar) that we don’t own. This other code can be a framework, a code developed by an other team in a big project or a legacy jar that we don’t want to touch.

Imagine the following use cases (all code running on CDI 2)

  • I’m compiling in CDI 1.x and one of the Jar (framework for instance) already migrated to CDI 2.0 firing async event where it use to fire sync events. Without activation on the observer side, I have all the chance to see my observer break. And if I decide to upgrade to CDI 2.0 I must have a way to activate / deactivate async call on given observers

  • I’m compiling in CDI 2.0 but use jar1 in CDI 1.0 and jar2 in CDI 2.0 coming from other teams. jar2 and jar1 are old related pieces of code communicating the event. The guys in jar2 had time to migrate to CDI 2.0 and switch most fire() to fireAsync(). Observer in jar1 will be called asynchronously if the default is to have async activated for all observers.

These example looks like corner cases but the side effect will be that no framework developers will switch to fireAsync() for the sake of defensive programming. So async event would have a serious adoption problem withotu this double activation. More than that, as we are designing a Java EE specification we must be committed to backward compatibility and cannot change behavior of old code, like it would do if we chose to not have activation on observer side.

Other change, corrections and clarifications

You can check the release notes of this early draft to discover the more minor changes we also introduced in the spec.

Implementation and TCK

TCK team and JBoss Weld team are currently working hard to provide a Reference Implementation for this draft. You’ll be notified as soon as there’ll be released.

We need you

To go on on this Early draft, we really need your feedback. The review period will be launch in the coming days by the JCP and will run for 90 days. You can give your feedback in many way:

Thank you for helping us making CDI one of the best programming model for Java and Java EE.

CDI 2.0 - A glimpse at the future

Posted by Thorben Janssen on Feb 23, 2015 | Comments


Before we have a look at the changes in the upcoming CDI 2.0 specification, lets talk about where they come from. Did you know that they were provided by the community, so maybe by you?

Before the work on JSR 365 started, former expert group members, the expert group members of other specifications and the community were asked which changes they would like to see in CDI 2.0. 260 developers provided their feedback in the community survey. Based on these information, the 6 main topics were defined:

  • modularity,

  • enhancements of the event system,

  • improvements for interceptors and decorators,

  • CDI for Java SE,

  • usage of Java 8 features and

  • SPI and context enhancements.

The work on these topic is organized in 6 workshops, one for each main topic. This allows the members to focus their efforts and the group to work on several topics in parallel. The work of each workshop is tracked in a publicly available workshop document. You can find a reference to each document in the following paragraphs.

The 3.0.0.Alpha releases of Weld, the CDI reference implementation, provide prototype implementations for the discussed features. The goal is to create an early proof of concept and to give the community a chance to try the new features and to provide feedback.
But please be aware, that these releases should not be used for production. They are only prototypes and the following releases are likely to contain incompatible changes.

Main Topics for CDI 2.0

OK, enough banter for now. Lets have a more detailed look at the current status of work and some new features in the following subsection.


One of the main topics for CDI 2.0 is modularization. In general, no one likes to consume a huge and heavy spec, if only a small part of it is required for the job. To make CDI easier to consume, the plan is to split the specification into different parts that provide different subsets of it. A project or JSR could then decide which parts it likes to use and define its dependencies accordingly.

The work on this topic is still in a very early state and so far, there are just some ideas on how the specification shall be modularized. The documented suggestion of 5 different parts that depend on each other will most likely not be the final version.
The new idea is to split the specification into 3 parts: CDI full with Java EE support, CDI full and CDI light. CDI full with Java EE support will provide the full feature set of the specification. CDI full and CDI light will only provide a subset of it. The Java EE support will be missing in both of them. Additionally, the support for Contexts and AOP will be missing in CDI light. We will have to see, if this will be the final version.

These are the current ideas on how to create a modular CDI specification. If you like to get more details or follow future discussions on this topic, you can find the workshop document here.

Enhancements of the events system

The enhancement of the existing event mechanics seems to be in heavy demand of the community and is one of the bigger topics for CDI 2.0. The main features requested by the community were to support asynchronous events and to get a better control about events and event observers. There are several ideas that are discussed at the moment and the latest Weld 3.0.0 Alpha releases provided prototype implementations for some of them.

Lets have a look at two of the momentarily discussed features. And again, the work is still ongoing and everything can still change.

Ordering of events

One of the requested enhancements is an option to order the event observers. The currently agreed solution is to use an approach similar to the priority definition for interceptors. The @Priority annotation can be used to define the priority of an event observer. The observers will process the event in ascending order of their priority. A working prototype for this feature was released with Weld 3.0.0.Alpha1. You can find more information about it in the release announcement.

Asynchronous events:

Up to now, events in CDI were processed synchronously. There are some workarounds to trigger asynchronous processing, e.g. using asynchronous EJBs, but this was outside the CDI specification and shall be changed with CDI 2.0.
The Weld 3.0.0.Alpha3 release provides a working prototype, which adds the method fireAsync to the Event interface. The processing of an asynchronous event is similar to the processing of a synchronous one. The event object is mutable and thread-safe and the event observers will process the event in the defined order. You can read more about it in the release announcement of Weld 3.0.0.Alpha3.

You can get an overview about all discussed changes and ideas in the workshop document.

Improvements for interceptors and decorators

There are several enhancements to interceptors and decorators in CDI that are planned for CDI 2.0. Some of them are to support AOP on custom or produced beans, to support AOP on inner calls and to improve the interceptor chaining. The work on these topics has not started yet. But there are some small enhancements that were already implemented with Weld 3.0.0.Alpha1.
As Jozef Hartinger described in his release announcement, support for repeatable annotations was added for qualifiers and interceptor bindings. And the javax.interceptor.InvocationContext interface was extended to make it easier to access the interceptor binding in the interceptor.

You will find more information about it in the workshop document as soon as the work has started.

CDI for Java SE

CDI requires an up and running CDI container to process its components. This is usually no problem in an Java EE environment because the application server is taking care of the CDI container. But this is different in an Java SE environment, where the container has to be booted by the application. The main problem is, that the specification does not define an API to boot the container. Therefore Weld and Open Web Beans provide its own proprietary APIs to do it and Apache DeltaSpike offers an uniform API on top of that. Beginning with CDI 2.0 the start of the container shall be defined in the standard.

The work on this topic is still ongoing and there are several open questions that need to be answered in the upcoming discussions. You can read about it in the workshop document.

Usage of Java 8 features

Java 8 was released in March 2014 and is therefore not used by the Java EE 7 specifications which were released in 2013. This will change with Java EE 8 and this means that CDI 2.0 can also make use of the new features.
The discussions about the influence of the new Java features on CDI are still in an early state, but there are several JEPs that seem to be applicable to improve the specification. Some of them, like the CompletionStage API and repeating annotations, are already used in the proposals for asynchronous events and repeatable interceptor bindings. But the usage of the new Java 8 features will not be limited to the new CDI features, there will also be talks on how to improve the existing parts of the specification.
The current ideas can be found in this document.

SPI and context enhancements

The work on SPI changes has also not started yet. Some goals of the CDI 2.0 specification will be to improve the access to all meta data created by CDI and to provide a way to add beans at runtime. The requested changes to provide a better control about contexts, especially to activate and deactivate them, will also require some SPI enhancements.
An additional huge topic will be the changes caused by the adoption of Java 8 and how to keep the SPI binary backward compatible.
The changes will be described in the workshop document.


As described in the previous paragraphs, the work on the CDI 2.0 specification is ongoing and there are lots of things that need further discussions. An early draft of the specification, which will contain the most stable new features, shall be completed in Q1 of 2015. The public review shall start in Q3 of 2015 and provide feedback for the final release. The final version of the CDI 2.0 specification shall be released in Q1 of 2016.