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

03.28.2011
| 143476 views |
  • submit to reddit
And a very common option is to use a field level injection as follows:

Code Listing: AutomatedTellerMachineImpl injecting SoapAtmTransport using new @Soap qualifier via setter method arg
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
	
    @Inject @Soap
    private ATMTransport transport;

From this point on, we are just going to use field level injection to simplify the examples.

Using @Qualfiers to inject multiple types into the same bean using


Let's say that our ATM machine uses different transport based on some business rules that are configured in LDAP or config file or XML or a database (does not really matter).

The point is you want it decided at runtime which transport we are going to use.

In this scenario we may want to inject three different transports and then configure a transport based on the business rules.

You are going to want to get notified when the injection is done and the bean is ready to go from a CDI perspective. To get this notifcation you would annotated an init method with the @PostConstruct annotation. Then you could pick which type of transport that you want to use.

Note the name of the method does not matter, it is the annotation that makes it an init method.

Code Listing: AutomatedTellerMachineImpl injecting multiple transports using new multiple qualifiers
package org.cdi.advocacy;

import java.math.BigDecimal;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

@Named("atm")
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
	
    private ATMTransport transport;
	
    @Inject @Soap
    private ATMTransport soapTransport;
	
    @Inject @Json
    private ATMTransport jsonTransport;
	
    @Inject @Json
    private ATMTransport standardTransport;

	
    //These could be looked up in a DB, JNDI or a properties file.
    private boolean useJSON = true;
    private boolean behindFireWall = true;

    @PostConstruct
    protected void init() {
                //Look up values for useJSON and behindFireWall		

        if (!behindFireWall) {
            transport = standardTransport;
        } else {
            if (useJSON) {
                transport = jsonTransport;
            } else {
                transport = soapTransport;
            }
        }

    }
	

    public void deposit(BigDecimal bd) {
        System.out.println("deposit called");

		
        transport.communicateWithBank(null);
    }

       ...
}

Try to follow the code above. Try to guess the output. Now compare it to this: Output
deposit called
communicating with bank via JSON REST transport
How did you do?

Using @Producer to make a decision about creation


This example builds on the last.

Perhaps you want to seperate the construction and selection of the transports from the AutomatedTellerMachineImpl.

You could create a Producer factory method that makes a decision about the creation and selection of the transport as follows:



Code Listing: TransportFactory deciding which transport to use/create
package org.cdi.advocacy;

import javax.enterprise.inject.Produces;

public class TransportFactory {
	
    private boolean useJSON = true;
    private boolean behindFireWall = true;

	
    @Produces ATMTransport createTransport() {
        //Look up config parameters in some config file or LDAP server or database

        System.out.println("ATMTransport created with producer makes decisions");
        
        if (behindFireWall) {
            if (useJSON) {
                System.out.println("Created JSON transport");
                return new JsonRestAtmTransport();
            } else {
                System.out.println("Created SOAP transport");
                return new SoapAtmTransport();
            }
        } else {
            System.out.println("Created Standard transport");
            return new StandardAtmTransport();
        }
    }

}

The advantage of this approach is that the logic to do the creation, is separate from the actual AutomatedTellerMachineImpl code.

This may not always be what you want, but if it is, then the producer can help you.

The output should be the same as before.

Output
ATMTransport created with producer makes decisions
Created JSON transport
deposit called
communicating with bank via JSON REST transport


Using @Producer that uses qualifiers to make a decision about creation


This example builds on the last.

You can also inject items as arguments into the producer as follows:



Code Listing: TransportFactory injecting qualifier args
package org.cdi.advocacy;

import javax.enterprise.inject.Produces;

public class TransportFactory {
	
    private boolean useJSON = true;
    private boolean behindFireWall = true;

	
    @Produces ATMTransport createTransport(	@Soap ATMTransport soapTransport, 
                        @Json ATMTransport jsonTransport) {
        //Look up config parameters in some config file
        System.out.println("ATMTransport created with producer makes decisions");

        if (behindFireWall) {
            if (useJSON) {
                System.out.println("return passed JSON transport");
                return jsonTransport;
            } else {
                System.out.println("return passed SOAP transport");
                return soapTransport;
            }
        } else {
            System.out.println("Create Standard transport");
            return new StandardAtmTransport();
        }
    }

}

In the above example, createTransport becomes less of a factory method and more of a selection method as CDI actually creates and passes the soapTransport and the jsonTransport.

Advanced topic: (Ignore this if it does not make sense) You may wonder why I create StandardAtmTransport and not inject it as a producer argument like soapTransport and jsonTransport. The problem is this createTransport is by default @Default and @Any but it overrides the StandardAtmTransport which is also by default @Default and @Any, but since StandardAtmTransport is overidden then if I inject @Default ATMTransport standardTransport as an argument then it tries to call createTransport since it is the @Default, which will then try to inject the argument standardTransport, which will then call createTransport, ad infinitum until we get a StackTraceOverflow. The solution is create a qualifier for the standard, say, @Standard and use that to do the injection, or create one for the createProduces production, say, @Transport. The key here is that the injection arguments of a producer have to have different qualifiers than the production method or all hell breaks lose, cats sleeping with dogs, pandimodium. Ok. Okay. The key here is that the injection arguments have to have different qualifiers than the production method or you will get a StackTraceOverflow as CDI calls your production method to resovle the injection point of you production method ad infinitum.

Here is the expected output.

Output
ATMTransport created with producer makes decisions
return passed JSON transport
deposit called
communicating with bank via JSON REST transport


Using multiple @Qualifiers at the same injection point to discriminate further


You can use more than one qaulifier to further discriminate your injection target.

To demonstrate this let's define to qualifiers SuperFast and StandardFrameRelaySwitchingFlubber. Let's say at the time we have two transports that are StandardFrameRelaySwitchingFlubber. Let's also say that you want to inject a transport that is not only a StandardFrameRelaySwitchingFlubber but also SuperFast.

First let's define the qualifier annotations as follows:

Code Listing: SuperFast defining a new qualifier
package org.cdi.advocacy;

...

@Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface SuperFast {

}



Code Listing: StandardFrameRelaySwitchingFlubber defining another new qualifier
package org.cdi.advocacy;

...

@Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface StandardFrameRelaySwitchingFlubber {

}

Ok, here is the code for the SuperFastAtmTransport which is marked with both the @SuperFast and the @StandardFrameRelaySwitchingFlubber qualifiers.

Code Listing: SuperFastAtmTransport uses two qualifiers
package org.cdi.advocacy;

@SuperFast @StandardFrameRelaySwitchingFlubber 
public class SuperFastAtmTransport implements ATMTransport {
    public void communicateWithBank(byte[] datapacket) {
        System.out.println("communicating with bank via the Super Fast 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.)

Comments

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!)

 Dave

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:

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


Into this:

@Inject
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

Walter,

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

Walter,

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

Walter,

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.
Thanks.

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.