Using CDI to Inject Dependencies into Unmanaged Objects

Contexts and Dependency Injection (JSR-299) is a great standard which is part of Java EE 6 and really simplifies Java EE programming, at least if you stay completely within the confines of Java EE.

However, applications that use CDI also need to be unit tested outside of the application server and in such cases it is useful to also perform CDI dependency injection outside of the container. Fortunately, Weld also support dependency injection in a Java SE environment.

When unit testing, the first idea would be to use CDI as much as possible to wire together the object graphs under test. But when doing this, several problems occur. First, certain managed objects such as EJBs and JPA entity manager and entitymanager factories are not recognized in a Java SE environment. Also, for unit test it should be possible to replace certain objects by test specific mocks. The latter is not supported by CDI as it supports only static configuration using “alternatives” in the beans.xml, whereas mock objects are usually dynamically generated so that the class name is not even known beforehand. Also, the APIs to use for programmatic dependency injection of CDI are a bit cumbersome.

As a result of all these points it is useful to create a simple wrapper library for performing programmatic dependency injection. The mini-framework is found in the support/inject utilities library. The two main concepts are an Injector used for injecting into an object and an InjectorBuilder for creating an injector. Using this concept, injection into a given object becomes easy, for example:

   MyPojo pojo = new MyPojo();

The mini framework uses the standard java.util.ServiceLoader mechanism to find an implementation of the injection technology to use. Therefore, using this mechanism, it is also possible to integrate other dependency injection technologies such as Guice and Spring.

For a working example, checkout the code at subversion.

The usefulness of this approach will become more clear if we take a look at mock testing, integration into 3rd party web frameworks such as Wicket, and some more advanced unit/integration tests in later posts.

This entry was posted in Java. Bookmark the permalink.

One Response to Using CDI to Inject Dependencies into Unmanaged Objects

  1. Hi there, You’ve done a fantastic job. I will certainly digg it and personally suggest to my friends. I am confident they’ll be benefited from this site.

Leave a Reply

Your email address will not be published. Required fields are marked *