Tagging a constructor with @Inject is essentially telling Guice where you want a dependency to be provided for you. Not only does this work for constructors but you can also apply @Inject to fields or methods. Which style you choose depends on the class's requirements and arguably your personal taste.

By "injection order is random," I mean that you should not rely on the order of injection. For example, if your class had two setters tagged with @Inject, you will never be sure which one will get called first by Guice. Guice often appears to use the order in which the methods were declared, but injection order can vary depending on the JVM you use, so assume the order is random.

Setter injection is a concept that is often misunderstood. If you're accustomed to using Spring, you've been probably using what it calls setter injection -- effectively, injection of JavaBean-style setters, which mean the methods you want to inject should be named setXXX, where XXX is the name of the single property that needs mutating. Guice, however, does not depend on this naming convention and can handle multiple parameters. The reasoning behind this is that it's also valid to want to inject methods that don't mutate a property but, for example, execute some kind of initialization logic right after object creation. But know that, as with Spring's setter injection, methods marked for injection get called with the appropriate values right after Guice creates the object for you. Once the object is fully initialized, Guice gets out of the way, and no more magic happens. So when you call the method yourself later, Guice does not magically provide some value for you.

What does work when it comes to injection is inheritance. If you subclass a class that features @Inject annotations, injection works as expected. First, the superclass gets injected, then the subclass. This only works for concrete classes though; you can't tag an implemented interface's members with @Inject and cross your fingers. Well you can, but it's not going to work.

It's also possible to inject static members or even members on objects that Guice didn't construct.

One final interesting point to note is that whichever type of injection you use, the target's visibility does not matter. Guice will inject anything tagged with @Inject whether it's private, package private, protected, or public.

Next up, I need to tell Guice that the chef wants a FortuneServiceImpl object when a FortuneService is requested.

Specifying an Implementation

Using the Module subclass I made previously, I can tell Guice which implementation to use for the Chef class's FortuneService, as illustrated in Listing 2:

You can also subclass the AbstractModule abstract class instead of implementing Module. This abstract class implements Module itself and exposes a no-argument configure() method. To purists, using AbstractModule probably looks a bit scarier than implementing the actual interface, but it's more concise:

Bootstrapping

To start using Guice, you create an instance of Injector. This central Guice type takes a collected set of Module implementations and injects our beloved Chef class. To create the Injector, I use one of the factory methods on the Guice class, which is a simple static class, to serve as a starting point for creating injectors. This method, createInjector(...), takes a varargs argument, which means you can specify zero or more modules, separated by a comma. For Chef, I only need one. I'll have one cookie, please. Listing 4 to the rescue!

FortuneServiceImpl doesn't have any dependencies itself, but if it did, Guice would have resolved its dependencies too. This recursive behavior allows you to use the Injector somewhere high up the stack in your application; Guice will then create the entire graph of dependencies below a requested object recursively.

The core Guice team has been reluctant to call this class a "container", as you would probably expect it to be named. Naming it Container would make you think that your objects sit somewhere in a container being managed, having a life cycle, and what not, which is not the way Guice does DI. The Injector injects your objects, and from then on, you're in control. Note: You will want to minimize the dependency on the Injector to avoid having a direct dependency on Guice. This is usually not very hard to do.

If you look around a bit, you'll see that createInjector(...) also has an overload that takes a Stage enumeration as the first parameter. The Stage of the Injector defines the mode of operation.

Using Stage.DEVELOPMENT means you'll have a faster start-up time and better error reporting at the cost of run-time performance and some up-front error checking. Stage.DEVELOPMENT is also the default. Using Stage.PRODUCTION on the other hand (shown in Listing 5), catches errors as early as possible and takes the full performance hit at start-up. But don't worry; Guice's overall performance is surprisingly good anyway. Just don't forget to switch on Stage.PRODUCTION for production code.

Injector i = Guice.createInjector(Stage.PRODUCTION, new ChefModule());

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!