BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Guice: Fast and Light Dependency Injection Container

Guice: Fast and Light Dependency Injection Container

Bookmarks

Guice is a new open-source Dependency Injection framework for Java 5 that is closing in on a 1.0 release. Guice is a very annotation-driven, lightweight framework that provides an alternative to Spring, for a certain set of features.

Guice, which is the depenecy injection engine in XWork, focuses on being small, fast, and requiring minimal code to use. The simple example from the Users’ Guide is:

With Guice, you implement modules. Guice passes a binder to your module, and your module uses the binder to map interfaces to implementations. The following module tells Guice to map Service to ServiceImpl in singleton scope:

public class MyModule implements Module {
 protected void configure(Binder binder) {
  binder.bind(Service.class)
  .to(ServiceImpl.class)
  .in(Scopes.SINGLETON);
  }
}

A module tells Guice what we want to inject. Now, how do we tell Guice where we want it injected? With Guice, you annotate constructors, methods and fields with @Inject.

public class Client {
  private final Service service;

  @Inject
 public Client(Service service) {
  this.service = service;
  }

 public void go() {
  service.go();
  }
}

The @Inject annotation makes it clear to a programmer editing your class which members are injected.For Guice to inject Client, we must either directly ask Guice to create an instance for us, or some other class must have Client injected into it.

Bob Lee, one of the project leads of Guice, has written a comparison piece of Spring and Guice.  In it he notes that Guice and Spring look very different, as Guice is focused on annotations.  Guice can be configured with strings, as in Spring, but they don't encourage it.  Guice requires Java 5 and supports generic types. 

Update:  Guice 1.0 has been released.

Rate this Article

Adoption
Style

BT