Contexts & Dependecy Injection for Java

CDI 2.0 - A glimpse at the future

Posted by Thorben Janssen on Feb 23, 2015 | Comments

Introduction

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.

Modularity

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.

Schedule

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.

CDI 2.0 first Face to face meeting feedback!

Posted by Antoine Sabot-Durand on Oct 20, 2014 | Comments

Last week we had the first CDI 2.0 Face to Face meeting in Brno (Czech Republic). Check what was discussed and the first CDI 2.0 orientations

Meeting Agenda

As you may know, CDI 2.0 project was launched only six weeks ago, so we are still in early discussion stage regarding CDI 2.0 design. Yet our workshop organisation was a good entry point to start going in more deep discussion. So we based our discussion on existing workshop documents. Here are the main decisions that came out from our discussion.

Parts introduction

Parts concept is not the most visible change we would introduce in CDI 2.0 but since it’s probably the one with more impact on spec organisation, we started with this point to know if we should go in that direction. That answer was yes. We also decided that each part would be independent from the other (i.e a bigger part wouldn’t depend from a smaller one but would integrate it) to solve API splitting issues. Having this principles accepted we talked about the possible parts and their content:

  • CDI Light: a lightweight version of CDI without Normal Scopes, Interceptors and Decorators that would allow proxy-free implementations. We worked on the API present in this Part, you can have a look to what we proposed on this branch

  • CDI Full: CDI as we know it today except for all the other spec integration (servlet, JSF, EJB, etc…​).

  • CDI Java EE : CDI full including integration with other specs

Events enhancement

The 2 main topics here were ordering and asynchronous events.

Asynchronous events.

The main idea was to adopt a different approach than the one in EJB today. Instead of using a @Asynchronous annotation and manage a Future<T> to deal with he end of asynchronous treatment, we looked for a way to provide callback to the event trigering.

The idea could be to add a fireAsync() method to the Event<T> and use Java 8 lambdas and add a functional interface like this :

@FunctionalInterface
public interface EventCallBack<T> {

    void doCallback(T callBack);
}

and use later like this

@Inject
Event<Payload> evt;


public void fireAsyncWithCallBack() {

    evt.fireAsync(new Payload(), callBack -> System.out.println("Job done”));
}

Off course this approach has to be more deeply investigate (we’ll do it on our coming event meeting) but it has a lot of advantages :

  • Introduce a more modern approach of async events processing like we have in other framework or technologies

  • Complete the EJB approach instead of duplicating it

  • Avoid asking Java EE EG to extract @Asynchronous form EJB to put it somewhere else (where?)

Events priority

Discussion on event priority was open some weeks ago. We tried to have a fresh look to the idea. The main point was about using @Priority annotation or not. The question is still not closed but we’re more in favor of the use of a value in @Observes annotation. This value would give the order of the observer (the lowest being the first). The main reason to choose this approach instead of @Priority is the fact that while being part of java common annotation (JSR 250) spec, @Priority is not present in Java SE. So using it would :

  • force us to ask for JSR 250 Maintenance release to allow priority on paramaters

  • add an extra dependency jar (for only one annotation) when using CDI Light in Java SE which seems against our "light" goal

The @Observes evolution evolution would give something like:

public void firstObserver(@Observes(1) Payload pl) {}

public void secondObserver(@Observes(2) Payload pl) {}

Priority value provided in javax.interceptor.Interceptor.Priority would be duplicated in CDI to avoid useless dependency on Interceptor spec while keeping the same approach / values. This ordering could be also used to order step in extensions.

Event Range

The idea behind event range would to provide a "scope" to events (i.e package, war, ear). It would prepare CDI event to become a server wide eventing system. The discussion came to the conclusion that while it’s rather easy to implement, it’s usage could be quite cumbersome. The idea was not discarded but we thought it was a good idea to check with community if the need was real.

Interceptors and Decorators (AOP) enhancement

There were a lot of discussions around enhancing interceptors and decorators. You’ll find the main topics below.

AOP on custom beans and producers

Conclusion was that it is doable but with certain limitations. Among them the fact that an interceptor on producer would be applied on all method of it (no obvious solution to target specifc methods).

We also discussed the syntax for binding interceptor to a produced bean. if you consider this code:

@Produces

@Loggable

public  Foo produceMap() {

    return new Foo();

}

@Loggable interceptor binding is bound to the method not the produced bean. We have to find an easy way to bind the interceptor to the produced bean. The only solution we found was to use a Stereotype with the interceptor binding and put it on the producer. Not a direct solution but rather elegant.

AOP on internal call vs self injection pattern

We already discussed about supporting AOP on call make in the same bean (calling intercepted B method from method A with interceptor triggering). After discussion, it seemed very difficult to introduce this new feature and AOP support on produced and custom beans at the same time. So the idea was to ease the use of self injection pattern, providing something like this.

public class MyBean {

  @Inject
  Self<MyBean> mySelf;

  @Loggable
  public methodB() {
    ...
  }

  public methodA() {
    mySelf.get().methodB();
  }
}

less elegant than having it directly on internal call but still useful.

Other AOP topics

We also discussed about the following topics:

  • relaunching the idea of supporting decorator without interface like it was requested in CDI-403 and before that in CDI-224.

  • standardise the partial bean feature from Deltaspike. For those who don’t know this feature an example can be found here.

Java SE support

We had a long discussion on Java SE support in CDI 2.0. To decide that we should just provide a class like this:

public class ContainerBoot {

    /**
     * Simple boot
     */
    static BeanManager initialize() {
      ...
    }

    /**
     * Boot with parameters
     */
    static BeanManager intialize(Map<?,?>) {
      ...
    }
    void shutdown() {}
}

Discussions are still going on on this topic.

SPI enhancement

Last but not least we also discussed about SPI enhancement. The main topic were:

  • Give the possibility to modify/register beans at runtime. The majority of present people were against this new feature. The ones in favor obtained that the door wouldn’t be closed now and that the community would be consulted to see if this need was "real". So we’ll be back on this feature and if you want to see it, stay tune to give it your support when we’ll ask for it.

  • Add SPI to activate/deactivate contexts. Right now built-in context cannot be activated / deactivated by third parties, forcing them to create their own implementation of such contexts instead of using the one provided by their implementation. This small modification will greatly ease CDI advanced integration in other spec or frameworks.

  • Add helpers to create CDI meta-data. Today it’s not very convenient to create an AnnotatedType or a custom Bean. We decided to explore the introduction of helpers inspired by Deltaspike Builders. They would be provided by lifecycle event

Conclusion

Here are the main topics we discussed during these 2 days. Other small feature will came to JIRA later. At this point there was only orientation and no final decision on any subject. So the door is still open for these as well as new feature. So don’t hesitate to give your advice andv your contribution to our workshop or Jira server.

Working method for CDI 2.0

Posted by Antoine Sabot-Durand on Oct 06, 2014 | Comments

Work on CDI 2.0 started at the beginning of september. As you may guess, specifying and releasing this new major version is a big challenge.

To put all chance on our side we are looking for a strong commitment from the community (as explained in our previous post). That’s why the way we’ll be organised is very important. Thus, when we started thinking about our working method we came up with the following requirements:

  • Keep the big picture of the spec in mind while working on all detail of each new / modified features

  • Have the right balance between "ideal specification" and the "specification only driven by implementation" approaches

  • Be able to welcome new contributors (even casual ones) without loosing them in spec history or advanced technical details at the beginning

  • Give visibility to third party (other JSR or future implementor) of the spec without forcing them to follow our ML, IRC, JIRA

  • Get feedback from the community easily while designing the spec

To satisfy these points we came to the idea of creating different workshop on big CDI topics (existing and new). To begin we identified these workshops:

  • Parts (modularity) : how we can make CDI more modular by extracting sub part in the spec to allow it to grow without becoming bloated

  • Java SE support : how CDI should work in Java SE and what SPI should we add or standardise to ease its integration in home brewed stacks

  • Events enhancement : bringing asynchronicity or ordering to events. Can it be extended to all Java EE

  • Interceptor & Decorator : AOP support on produced or custom bean. Work with interceptor spec to add AOP on inner call

  • SPI enhancement for integration : give access to all metadata produced by the container, give control of CDI from outside code, support Bean addition / modification @ Runtime

  • Contexts enhancement : go beyond the the thread-bound request-response model used by context today to support new application architecture

  • Java 8 enhancement : see how new features in java 8 (type annotation, annotation repetition, lambdas, streams, default methods, type inference…) could enhance CDI in existing and new features.

To ease this big picture approach we also adopted this following step to deal with each workshop:

  1. Blueprint draft : the workgroup lead propose a draft document describing his global idea of how the future should work

  2. Draft discussion The draft is commented, amended, enhanced by the group which can react to the doc by proposing new ideas. and When people feel ready by the EG

  3. Detailled task / requirement: after the discussion, each adopted concept are translated in on or more tickets in our Jira to follow their realisation to start more detailled discussion

  4. Spec and TCK enhancement: each task is translated to the new specification document and translated to the TCK

Of course these steps are more guidelines than a strong workflow, it’s a way to ease contribution not constraint it. It will probably evolve with time.

On our home page you’ll find the list of each workshop and their current status and links (working doc, Jira EPICS, etc…​). Please feel free to check these links and give your feedback and don’t heistate to contribute with your idea on this documents.

CDI 2.0 needs you

Posted by Antoine Sabot-Durand on Aug 26, 2014 | Comments

Uncle Duke The work on CDI 2.0 specification is about to start in the coming weeks. We have a lot of ambitious features on the table as you can check in our previous article, but we also have only 18 months to specify and implement them. Without community help, we probably won’t be able to do all the change we are planning, so your contribution is precious to us. In this post I’ll explain the multiple ways you can be part of it, even if you only have a few hours a week to help us and/or are not a CDI, JCP or a Java expert. Let’s check the 3 main question most of you have regarding contribution and try to answer them:

  • Why should I contribute?

  • Is it possible for me to contribute?

  • How do I start contributing?

Why should I contribute to CDI 2.0?

Contributing to a specification like CDI looks like any other Open Source contribution (by the way CDI specification and deliverable are under the Apache License version 2) yet it’s very different. The following points will detail these differences.

Working on Architecture and concepts first

The biggest difference between working on a standard OSS project and a specification is probably the fact that the first job is to write detailled documentation (the specification document). Regarding specification document, the content should be very accurate and respect a certain set of rules among them:

  • use an homogenous style in simple yet understandable english across the doc,

  • as specification cannot be changed easily, the work must be very precise, consequences of a choice must be analysed deeply and ambiguities in definitions shouldn’t exist,

  • stick to Java language Specification (JSL) rules and terms,

  • avoid "denormalization": the specification should use cross references to point to an existing definition instead of duplicating it,

  • avoid mentioning how features should be implemented while keeping in mind that specified features will have to be implemented at the end.

Participating to code writing.

Specification is useless without implementations. So after (and sometimes while) thinking, comes code writing. First the API, the code that all specifications will have to implement and then as a proof of concept of the specification we have to provide the RI (reference implementation) and TCK (Technology Compatibility Kit) which is mandatory for developing other implementations. So you can also be useful by contributing to JBoss Weld and the CDI TCK which is the translation of the specification in a test suite. Off course these will ask more time and probably more skills for a contribution.

Contributing to the future of Java EE and Java SE

CDI 2.0 will be part of Java EE 8 but also targets Java SE. Therefore, we’d like to make CDI the Dependency Injection standard for Java. It already plays this role for Java EE. So contributing to the CDI 2.0 specification is a way to be part to the future of Java and Java applications architecture.

Being at the source of a lot of other projects

Working on CDI specification is also a way to indirectly work at (and thus, have impact on) other projects linked to it. The implementations (Apache OpenWebBeans and JBoss Weld) are off course the obvious ones, but today there are a lot of other open source frameworks or projects out there based on CDI. Apache Deltaspike, VRaptor or Openbravo are some example of these (you can also consider most of JBoss Java frameworks which use CDI to be integrated). Working on CDI is a way to help these projects to become better or give you the knowledge to contribute to them in the future to help them getting the best of CDI 2.0 when it will be released.

Is it possible for me to contribute?

Most people disqualified themselves when it comes to contribute to a JSR. The 3 most frequent reason given are:

  • the technical level,

  • the lack of time or,

  • the "paperwork" tied to such a contribution.

Let’s review these "good" excuses that could make one thinks "contributing is not for me"

Technical level

Ok, if you are an absolute beginner in Java and CDI, it will be hard to help without making others loose their time. But as you’re reading these lines, you are probably not an absolute beginner ;). One of our goal on CDI 2.0 is to make the specification as easy as possible to read. So even if you are not a top notch Java specialist, your reading skill and feedback on badly written, ambiguous or hard to understand part will be very precious to the Expert Group. Regarding Java Level, CDI 2.0 will leverage a lot of new features coming with Java SE 8 on which most of the contributors will have very little experience. So, on this topic specialists will be the exception. To make short, the minimum level to contribute is to have a reasonable knowledge on Java (enough to know your unknown and where to look to learn), have already used CDI in development, have a good knowledge of its features (DI, Events, AOP, Extensions…​) and be able to read english. That makes a lot of people qualified to help.

Time

From the previous point you can understand that there is no minimum amount of time for contribution. For instance you can read a specification chapter and propose corrections or remarks on it, it will take you 2 or 3 hours on the 18 months of the specification. Now the best would be to provide a few hours a week. To help people that want to contribute and don’t have much time, we’ll try to provide a monthly synthesis of topics worked on the project to spare their time and avoid the "I’d like to do something but I don’t have time to dig thru all the mailing list and Jira message to figure out what to do". These reports will also be useful for the EG members to have a big picture vision of the work regulary.

Paper work

To be officially enrolled on a JCP Expert Group requires a little paper work. You’ll have to create an account on jcp.org and sign the Java Specification Agreement (JSPA). You’ll probably have to ask you employeer an agreement to contribute. And then ask the spec lead to be part of the JSR. On the JSR side, we never refused a member in the EG in the past and plan to continue like that for the new JSR

The good news is that we also accept non official contributions as any other Open Source project using ASL2. So if you don’t feel like signing JCP stuff, you can still participate to discussion on the Mailing list, the IRC channel or our JIRA site. You can even send pull request on the project. The only difference will be that you won’t be mentioned as a member of the expert group on the JCP website.

So to make short. You can start contributing with no paper work. Stay anonymous during all the project or decide to officially join the EG at any time before the end of the JSR. The only limit would be if you start doing big contribution. In this case we’ll probably ask you to join EG to avoid any future IP issues.

How do I start contributing?

The best place to start is probably the Mailing List, or if you want a more informal you can begin with the IRC channel(#cdi-dev on freenode). All the information regarding communication channel of the spec is detailled on the contribute page.

You also should start reading the existing specification to become familiar with its content and its style.

Finally, as the specification is written in asciidoc (with the excellent asciidoctor implementation), you should also start learning it. The best place is probably the Asciidoctor user manual. As we’re using asciidoctor maven plugin to generate the doc you won’t have to install asciidoc toolchain, only Maven. You’ll also nedd a text editor with optionally plugins to help writing asciidoc. Atom editor with asciidoc language and asciidoc preview plugins is a good solution, but there are plenty of others depending on your taste and current tools.

What’s next?

We are currently preparing the organization of the work around the specification. The goal is to be as efficient as possible regarding contribution. The Mailing List is the best place to stay tuned. In the meantime you can do "homework" with the existing material.

Conclusion?

We are trying to make CDI 2.0 a very open specification to give to the community the possibility to contribute easily to this great project. We are thrilled to count you onboard for any contribution (big or small) you’ll be able to do, making CDI 2.0 your specification.

What's in CDI 2.0 JSR proposal?

Posted by Antoine Sabot-Durand on Jul 28, 2014 | Comments

A few days ago, we submitted the official proposal for CDI 2.0. This new version is focused on 2 main goal:

  1. Adding Java SE support to CDI

  2. Add modularity to CDI to ease its integration with other specification or framework.

Off course a lot of feature and enhancement will come from this 2 goals and we’ll add a few more if possible. Let’s check what’s on the menu.

A new name

Not the most important part, but as we plan supporting Java SE, we slightly changed the name of the specification. Previously, the full name of CDI was: Contexts and Dependency Injection for Java EE. The proposed new name is: Contexts and Dependency Injection for Java. So to SE we go ;).

New features and enhancement proposed

Beyond the two main points introduced above (or because of them), we have the following features in mind

Identify the Java EE part in CDI

We have a lot of work to prepare the Java SE support in CDI. The first will be to check what’s is pure CDI and what’s is link to Java EE. So for CDI 2.0, The specification and TCK require a significant overhaul to be split into two parts.

  1. Part 1: The core CDI programming model (usable in EE and SE as well)

  2. Part 2: Java EE integrations for CDI (i.e. all the feature that won’t be available when working in Java SE).

Some of the splitting is straight forward (thre’s no EJB in Java SE), other could bring some discussion and extra work (do we want to support @Transactional in Java SE and how?).

Defining a portable bootstrap API for CDI.

Currently CDI does not define an API for bootstrap, instead relying on a Java EE deployment to start the container. To add support for Java SE, we really need such an API. Additionally, we would like to introduce a programmatic API for binding beans, allowing much greater flexibility for portably wiring a container.

Enhance the CDI context model

The context model in CDI is based around the thread-bound request-response model. This model is more prevalent in web applications than elsewhere, and, also is less pervasive than it once was. We would like to overhaul the context model to allow the application or container to portably push the active context to CDI when it requires the use of CDI. This change would be largely transparent to applications, and we might want to consider an API facade over it.

Introduce modularity to CDI.

One of the most often given reason by other JSR or frameworks to limit their CDI adoption is the size of the specification. Too big, too many features. CDI is becoming an important component model in Java EE, and we think that learning from the experience of long running specifications of specifications (like EJB) is important. Before we starting adding features to CDI, we want to see if we can introduce “parts”, to avoid creating a spec that gives the impression of being big and heavy. There’s already some preparation work around this topic. For instance JAX-RS asked if it was possible to only have only the event part of CDI. Other discussion with the future java config specification are dealing with a "type discovery" part. One of the most asked module is a lightweight container, which takes the annotations specified by the @Inject specification, defines the behavior of the container (which @Inject failed to do), and adds a couple of popular features from CDI such as producer methods. This will allow much wider adoption of CDI in the Java world, and provide a great stepping stone between Java SE, a servlet container, OSGi and a full Java EE server.

Other features

Off course there’ll be other features introduced in CDI 2.0. They come from

  1. Standardization of existing extension like the ones created in Apache Deltaspike project

  2. Request from our CDI 2.0 survey which will close on july 31st

  3. Features coming from other Java EE 8 spec, like @Transactional was introduced in CDI 1.1 after it was extracted from EJB spec.

Next Step

The proposal is being discussed among JCP executive committee members and if everything goes well it should be accepted in the coming days. At this moment we’ll start forming the CDI 2.0 Expert Group and begin effective work around this specification. We hope deliver the final spec in Q4 2015 or Q1 2016. Stay tuned on this blog or on @cdispec to have fresh news regarding the spec and the coming expert group.