Rick has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

CDI Dependency Injection - An Introductory Tutorial Part 1 - Java EE

  • submit to reddit

By default, CDI would look for a class that implements the ATMTransport interface, once it finds this it creates an instance and injects this instance of ATMTransport using the setter method setTransport. If we only had one possible instance of ATMTransport in our classpath, we would not need to annotate any of the ATMTransport implementations. Since we have three, namely, StandardAtmTransport, SoapAtmTransport, and JsonAtmTransport, we need to mark two of them as @Alternative's and one as @Default.

Step 3: Use the @Default annotation to annotate the StandardAtmTransport

At this stage of the example, we would like our default transport to be StandardAtmTransport; thus, we mark it as @Default as follows:

Code Listing: StandardAtmTransport using @Default
package org.cdi.advocacy;

import javax.enterprise.inject.Default;

public class StandardAtmTransport implements ATMTransport {

It should be noted that a class is @Default by default. Thus marking it so is redundant; and not only that its redundant.

Step 4: Use the @Alternative to annotate the SoapAtmTransport, and JsonRestAtmTransport.

If we don't mark the others as @Alternative, they are by default as far as CDI is concerned, marked as @Default. Let's mark JsonRestAtmTransport and SoapRestAtmTransport @Alternative so CDI does not get confused.

Code Listing: JsonRestAtmTransport using @Alternative
package org.cdi.advocacy;

import javax.enterprise.inject.Alternative;

public class JsonRestAtmTransport implements ATMTransport {


Code Listing: SoapAtmTransport using @Alternative
package org.cdi.advocacy;

import javax.enterprise.inject.Alternative;

public class SoapAtmTransport implements ATMTransport {

Step 5: Use the @Named annotation to make the AutomatedTellerMachineImpl easy to look up; give it the name "atm"

Since we are not using AutomatedTellerMachineImpl from a Java EE 6 application, let's just use the beanContainer to look it up. Let's give it an easy logical name like "atm". To give it a name, use the @Named annotation. The @Named annotation is also used by JEE 6 application to make the bean accessible via the Unified EL (EL stands for Expression language and it gets used by JSPs and JSF components).

Here is an example of using @Named to give the AutomatedTellerMachineImpl the name "atm"as follows:

Code Listing: AutomatedTellerMachineImpl using @Named
package org.cdi.advocacy;

import java.math.BigDecimal;

import javax.inject.Inject;
import javax.inject.Named;

public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {


It should be noted that if you use the @Named annotations and don't provide a name, then the name is the name of the class with the first letter lower case so this:

public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {


makes the name automatedTellerMachineImpl.

Step 6: Use the CDI beanContainer to look up the atm, makes some deposits and withdraws.

Lastly we want to look up the atm using the beanContainer and make some deposits.

Code Listing: AtmMain looking up the atm by name
package org.cdi.advocacy;


public class AtmMain {


    public static void main(String[] args) throws Exception {
        AutomatedTellerMachine atm = (AutomatedTellerMachine) beanContainer

        atm.deposit(new BigDecimal("1.00"));



When you run it from the command line, you should get the following:

deposit called
communicating with bank via Standard transport

You can also lookup the AtmMain by type and an optional list of Annotations as the name is really to support the Unified EL (JSPs, JSF, etc.).

Code Listing: AtmMain looking up the atm by type
package org.cdi.advocacy;


public class AtmMain {


    public static void main(String[] args) throws Exception {
        AutomatedTellerMachine atm = beanContainer.getBeanByType(AutomatedTellerMachine.class);
        atm.deposit(new BigDecimal("1.00"));


Since a big part of CDI is its type safe injection, looking up things by name is probably discouraged. Notice we have one less cast due to Java Generics.

If you remove the @Default from the StandardATMTransport, you will get the same output. If you remove the @Alternative from both of the other transports, namely, JsonATMTransport, and SoapATMTransport, CDI will croak as follows:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: javax.enterprise.inject.AmbiguousResolutionException: org.cdi.advocacy.AutomatedTellerMachineImpl.setTransport: 
Too many beans match, because they all have equal precedence.  
See the @Stereotype and <enable> tags to choose a precedence.  Beans:
    ManagedBeanImpl[JsonRestAtmTransport, {@Default(), @Any()}]
    ManagedBeanImpl[SoapAtmTransport, {@Default(), @Any()}]
    ManagedBeanImpl[StandardAtmTransport, {@javax.enterprise.inject.Default(), @Any()}]

CDI expects to find one and only one qualified injection. Later we will discuss how to use an alternative.

Using @Inject to inject via constructor args and fields

You can inject into fields,constructor arguments and setter methods (or any method really).

Here is an example of field injections:

Code Listing: AutomatedTellerMachineImpl.transport using @Inject to do field injection.
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
    private ATMTransport transport;

Continue reading... Click on the navigation links below the author bio to read the other pages of this article.

Be sure to check out part II of this series as well: Part 2 plugins and annotation processing !

About the author
This article was written with CDI advocacy in mind by Rick Hightower with some collaboration from others. Rick Hightower has worked as a CTO, Director of Development and a Developer for the last 20 years. He has been involved with J2EE since its inception. He worked at an EJB container company in 1999. He has been working with Java since 1996, and writing code professionally since 1990. Rick was an early Spring enthusiast. Rick enjoys bouncing back and forth between C, Python, Groovy and Java development.

Although not a fan of EJB 3, Rick is a big fan of the potential of CDI and thinks that EJB 3.1 has come a lot closer to the mark.

Rick Hightower is CTO of Mammatus and is an expert on Java and Cloud Computing. Rick is invovled in Java CDI advocacy and Java EE. CDI Implementations - Resin Candi - Seam Weld - Apache OpenWebBeans

Published at DZone with permission of its author, Rick Hightower.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Dave Macpherson replied on Mon, 2011/03/28 - 10:21am

"...Thus marking it so is redundant; and not only that its redundant"


This made me laugh. Good one!

(Good intro article too!)


Josh Marotti replied on Mon, 2011/03/28 - 2:28pm

I have to admit, I hate the qualifier is put into an annotation.  Why can't we inject and qualify by name we used from the @Named annotation instead (to kill the coupling that will occur with a new annotation)?

Turn this:

public void setTransport(@Soap ATMTransport transport) {
   this.transport = transport;

Into this:

public void setTransport(@Qualified("soap") ATMTransport transport) {
   this.transport = transport;

It may not be as readable, but doesn't require the annotation, and, thereby, code coupling.  Perhaps it can already do this and you just haven't mentioned it?


Rick Hightower replied on Mon, 2011/03/28 - 3:23pm

Josh Marotti, There is a way to do something similar to that. I discuss it in the second article in this series. "There could be an explosion of qualifers annotations in your project. Imagine in our example if there were 20 types of transports. We would have 20 annotations defined." "This is probably not want you want. It is okay if you have a few, but it could quickly become unmanageable." CDI allows you to descriminate on members of a qualifier to reduce the explosion of qualifiers. Instead of having three qualifier you could have one qualifier and an enum (or a string like you have above although this is frowned upon in CDI). Then if you need more types of transports, you only have to add an enum value instead of another class. There are examples of this in the next article.

Reza Rahman replied on Mon, 2011/03/28 - 4:25pm in response to: Rick Hightower

You indeed can use @Named as a qualifier.

The trade-off is sacrificing Java-based type-safety and readability as mentioned. The way I see it personally, in most real-life projects, you will only really need a handful of qualifers, so I don't see more type-safe qualifiers as a big issue, but an overall improvement over traditional name based injection point qualification (in fact I suspect it is an evolutionary quirk arising fom the heavy XML dependence of early DI frameworks).

Walter Bogaardt replied on Mon, 2011/03/28 - 6:36pm

Cheers Rick,

Claming a little ignorance, but will you also be illustrating testing an application via mock objects using CDI. In spring using the xml mappings its easy as swaping out the xml files, but be interested in annotation based solution to this.



Rick Hightower replied on Mon, 2011/03/28 - 10:02pm


The short answer is Alternatives. I don't remember if I cover them here or in the next article. (I wrote the example code already).

The longer answer will have to wait until I put the kids to bed.

Cloves Almeida replied on Mon, 2011/03/28 - 10:18pm

Seam 3 (designed as a set of extensions on top of CDI) has a XML config module that could achive such flexibility.

Rick Hightower replied on Mon, 2011/03/28 - 11:23pm


Also you can use alternatives. There is a section in this tutorial on alternatives. Using @Alternative to select an Alternative Earlier, you may recall, we defined several alternative transports, namely, JsonRestAtmTransport and SoapRestAtmTransport. Imagine that you are an installer of ATM machines and you need to configure certain transports at certain locations. Our previous injection points essentially inject the default which is the StandardRestAtmTransport transport.

You can scan for it.

Here is a link to the section in the wiki version of this tutorial Alternatives

As cloves was saying if you wanted to use the XML files. Seam has XML CDI plugin that is similar to what you would expect in a spring context xml file. Resin also supports an XML file version. In most cases, you should be able to use Alternatives.

Rick Hightower replied on Mon, 2011/03/28 - 11:24pm


One more thing. There are several unit testing frameworks for CDI. We plan on writing tutorials about them in the future. There is a lot more to come. There is a lot out there. CDI is nascent but coming together quickly.

Josh Marotti replied on Tue, 2011/03/29 - 11:08am in response to: Rick Hightower

I saw that, but it is still user-based created annotations or enums.  When I load spring, for example, with just a config.xml, the actual objects are 'pure' in that they don't have external annotations or objects.  I liked the idea of using annotations in spring, but it coupled the objects to spring, which I felt was dirty.  When CDI came out, it causes a dependency to J2EE 6, but at least that was something that would have been loaded if we reused the objects in another project.  The necessity of bringing the custom annotations or enums, though, makes me feel that it is back to where we were with spring... bringing along other coupled code for an object that can almost stand alone.


I'm not saying it's the end of the world or anything.  It is cleaner than what we have now.  I just am wishing for a blue-sky perfectionism that we just don't find in architecture.

Rick Hightower replied on Tue, 2011/03/29 - 12:36pm in response to: Josh Marotti

As mentioned earlier, the Seam Weld project has a CDI plugin that provides a "config.xml" that is similar to Springs. Since it is a CDI plugin (called extensions), it should work on any standard CDI implementation. Expect a future article on using this plugin. Also Resin CANDI (another CDI implementation) has XML support, and this CDI XML support is also how you configure the server itself so the whole thing uses CDI throughout.

Since the Seam CDI Weld project has a nice plugin, it might become the de facto standard for when you want XML instead of annotations. Personally, I prefer to use the annotations whenever possible and keep the XML as small as possible.

Andy Gibson replied on Tue, 2011/03/29 - 12:43pm

Josh the benefits of qualifiers, or qualifiers with Enums is that you get type safety when defining injection points and items to be injected. You could just use named but thats just attaching an untype safe name to the bean.

I see what you are saying about having to drag external qualifiers in there, and I have two answers for that.

First the qualifier could be regarded as part of your object semantics, the SoapTransport class really is a @Transport and marking it with that qualifier is along the lines of implementing the Transport interface. Think about it, you don't need to implement the Transport interface, you do it to make it type safe and to take advantage of polymorphism. Likewise you add a qualifier to make it type safe and to take advantage of looking up beans of similar types but with different qualifiers (i.e. semantic polymorphism or something!)

 We don't get rid of an interface to keep our objects pure when we only use one implementation of the interface (there are times we should but we don't always). Same way we don't throw out qualifiers just because we aren't always accessing the beans using the qualifier.

Second option is to can create your pure SoapTransport class with no CDI annotations and have a CDI aware transport factory with a method to create a SoapTransport that is annotated with @Produces @Transport(TransportType.SOAP) . You would have to build the instance (or get it from the CDI container) and return it.

However, you run into problems because if the SoapTransport class needs an xyz bean injecting into then its not going to happen automatically because you didn't define the injection point with @Inject because your bean knows nothing about CDI. At which point, you have to handle your own injection like you would if you had to define it in xml.

In this case CDI makes you do your manual injections in type safe code rather than in untype safe xml, usually with no code assist either.

Thanks for your thoughts,  I think this is a good idea for a blog post.


Reza Rahman replied on Tue, 2011/03/29 - 2:59pm in response to: Rick Hightower

Just to be absolutely clear, you can put *all* meta-data in XML with CDI if you so wish (of course you'd be reverting back to name based qualification).

XML config is definitely worth a look: http://docs.jboss.org/seam/3/config/latest/reference/en-US/html/. As far as XML goes, it is far more compact, readable and type-safe because it is schema driven as opposed to most legacy XML configuration (CanDI XML is the same way). In fact, I wish we could adopt the model for Java EE overall.

Now, I doubt it's anything that anyone would recommend because other than a preference to remove all meta-data from Java code, there are few benefits to that approach and a lot of pitfalls - particularly because injection related meta-data hardly changes all that much and is likely semantically linked to the code anyway.

BTW, chances are CDI XML configuration might be standardized in Java EE 7.

Rick Hightower replied on Tue, 2011/04/05 - 4:30pm

Part 2 is out: Part 2
It is a bit shorter than Part 1

Rick Hightower replied on Wed, 2011/04/06 - 7:28pm

FYI... (like XML) and tags Foo were getting stripped out by the output processing of JavaLobby. Essentially tags that are not allowed are still in the content mgmt system, but not processed.

I changed all < to < and all < to >. I actually have a Python text processor that I wrote that converts from google WIKI markup into other markups so it was as easy as adding
line = line.replace("<", "<").replace(">",">").
To the part that does the code processing.

James Weitlauf replied on Thu, 2011/04/14 - 7:39am

Is it possible to mix the DI between xml and annotations, ie use @Inject for a bean that I configured using xml?  Reason I ask is because I configured my Hibernate session factory in the xml but I need that injected into my Dao, which gets injected into Foo.

So I would like to @Inject the Dao into Foo and @Inject my sessionfactory into my Dao.

I am using Spring 3 if that matters.

Nevermind, I found my answer... amazing what you can find if you read the documentation.

Carla Brian replied on Tue, 2012/05/29 - 9:10am

Good thing I stumbled upon in this post. I am new to this application. Thanks for sharing your insights. - Byron Pederson

David Espinosa replied on Sat, 2014/03/29 - 10:44pm

 This is the best tutorial about CDI.

Dinoop Paloli replied on Sat, 2014/03/29 - 3:35pm

Hi, What is beanContainer Object and how can I get it? I am using Jboss 7 to deploy the above examples

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.