Channels ▼
RSS

Open Source

Google Guice


Preparing the Code

Take a look at Listing 1.

public class Chef {
private final FortuneService fortuneService;
  @Inject
    public Chef(FortuneService fortuneService) {
    this.fortuneService = fortuneService;
  }
  public void makeFortuneCookie() {
   new FortuneCookie(fortuneService.randomFortune());
  }
}
Listing 1: FortuneService that Gives Out Fortunes

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:

public class ChefModule implements Module {
  public void configure(Binder binder) {
   binder.bind(FortuneService.class)
    .to(FortuneServiceImpl.class);
  }
}
Listing 2: Telling Guice Which FortuneService Service to Use

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:

public class ChefModule extends AbstractModule {
   protected void configure() {
     bind(FortuneService.class).to(FortuneServiceImpl.class);
   }
}
Listing 3: AbstractModule Saves You Some Keystrokes

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!

public class FortuneApplication {
public static void main(String[] args) {
     Injector i = Guice.createInjector(new ChefModule());
    Chef chef = i.getInstance(Chef.class);
  chef.makeFortuneCookie();
  }
}
Listing 4: Bootstrapping Guice and Creating Chef

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());
Listing 5: Specifying a Stage for the Injector


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

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.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video