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
| 154161 views |
  • submit to reddit


Code Listing: AutomatedTellerMachineImpl.transport using @Inject to do constructor injection.
...
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
	
    @Inject 
    public AutomatedTellerMachineImpl(ATMTransport transport) {
        this.transport = transport;
    }

This flexibility allows you to create classes that are easy to unit test.

Using simple @Produces


There are times when the creation of an object may be complex. Instead of relying on a constructor, you can delegate to a factory class to create the instance. To do this with CDI, you would use the @Produces from your factory class as follows:



Code Listing: TransportFactory.createTransport using @Produces to define a factory method
package org.cdi.advocacy;

import javax.enterprise.inject.Produces;

public class TransportFactory {

    @Produces ATMTransport createTransport() {
        System.out.println("ATMTransport created with producer");
        return new StandardAtmTransport();
    }

}

The factory method could use qualifiers just like a class declaration. In this example, we chose not to. The AutomatedTellerMachineImpl does not need to specify any special qualifiers. Here is the AutomatedTellerMachineImpl that receives the simple producer.



Code Listing: AutomatedTellerMachineImpl receives the simple producer
import javax.inject.Inject;
import javax.inject.Named;

@Named("atm")
public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
	
    @Inject
    private ATMTransport transport;
        ...

Check your understanding by looking at the output of running this with AtmMain.

Output
ATMTransport created with producer
deposit called
communicating with bank via Standard transport


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.

If I need to install a different transport, all I need to do is change the /META-INF/beans.xml file to use the right transport as follows:

Code Listing: {classpath}/META-INF/beans.xml
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <alternatives>
        <class>org.cdi.advocacy.JsonRestAtmTransport</class>
    </alternatives>
</beans>

You can see from the output that the JSON REST transport is selected.

Output
deposit called
communicating with bank via JSON REST transport

Alternatives codifies and simplifies a very normal case in DI, namely, you have different injected objects based on different builds or environments. The great thing about objects is they can be replaced (Grady Booch said this). Alternatives allow you to mark objects that are replacements for other objects and then activate them when you need them.

If the DI container can have alternatives, let's mark them as alternatives. Think about it this way. I don't have to document all of the alternatives as much. It is self documenting. If someone knows CDI and they know about Alternatives they will not be surprised. Alternatives really canonicalizes the way you select an Alternative.

You can think of CDI as a canonicalization of many patterns that we have been using with more general purpose DI frameworks. The simplification and canonicalization is part of the evolution of DI.



Code Listing: Using @Qualifier to inject different types


All objects and producers in CDI have qualifiers. If you do not assign a qualifier it by default has the qualifier @Default and @Any. It is like a TV crime show in the U.S., if you do not have money for a lawyer, you will be assigned one.

Qualifiers can be used to discriminate exactly what gets injected. You can write custom qualifiers.

Qualifiers work like garanimal tags for kids clothes, you match the qualifier from the injection target and the injection source, then that is the type that will be injected.

If the tags (Qualifiers) match, then you have a match for injection.

You may decide that at times you want to inject Soap or Json or the Standard transport. You don't want to list them as an alternative. You actually, for example, always want the Json implementation in a certain case.

Here is an example of defining a qualifier for Soap.



Code Listing: Soap runtime qualifier annotation
package org.cdi.advocacy;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import javax.inject.Qualifier;


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

}

Notice that a qualifier is just a runtime annotation that is marked with the @Qualifier annotation. The @Qualifier is an annotation that decorates a runtime annoation to make it a qualifier.

Then we would just mark the source of the injection point, namely, SoapAtmTransport with our new @Soap qualifier as follows:



Code Listing: SoapAtmTransport using new @Soap qualifier
package org.cdi.advocacy;

@Soap
public class SoapAtmTransport implements ATMTransport {

    @Override 
    public void communicateWithBank(byte[] datapacket) {
        System.out.println("communicating with bank via Soap transport");
    }

}
Next time you are ready to inject a Soap transport we can do that by annotating the argument to the constructor as follows:

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

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

You could also choose to do this via the setter method for the property as follows:

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

    @Inject 
    public void setTransport(@Soap ATMTransport transport) {
        this.transport = 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.