BT
x Your opinion matters! Please fill in the InfoQ Survey about your reading habits!

Annotation-Driven Dependency Injection with Google Guice 3.0

by Michael Floyd on Apr 20, 2011 |

Late last month Google released Guice 3.0 to the development community, and in so doing added several extensions on top of the usual bug fixes and patches. Guice, which was originally introduced in 2006, is a Java framework that implements the dependency injection (DI) design pattern. The motivation behind Guice was to make it easier for programmers to write DI code by reducing the need to write boilerplate factories, as is typical when manually injecting dependencies. Instead of writing factories to handle the injections, a developer simply creates a module that maps the interfaces to their implementations, then uses an annotation (like @Inject) on the constructor. Within the module, the programmer writes something like: bind(myInterface.class).to(myImplementation.class);

Once the module is configured just add an @Inject annotation to the client code. Bootstrapping the injector takes just four lines of code: Simply create an injector that points to the module, then use the injector to getInstance() of that module.

The above example uses constructor injection. But Guice supports other types of injections including method (setter) injection, and field injection. This latter form of injection has been criticized because it creates code that can be more obscure and less easy to maintain. The Guice team discourages the use of filed injection for this reason.

A key feature of Guice is that is type safe in that type checking is performed at compile time and the injection returns the same type that is injected. Scopes are handled declaratively using annotations, so developers can define a scope simply by creating an annotation.

 

New in 3.0

The most notable change to Guice 3.0 is the inclusion of a fully compliant JSR 330 injector. (JSR 330 was finalized in 2009.) In fact, “Guice 3.0 is the reference implementation for JSR 330,” according to Dhanji Prasanna of the Guice development team.

Because there is still a need to write factory code, Guice 3.0 adds assisted injection, which automatically generates factory implementations, alleviating the need to write boilerplate code. There are also new Binder methods and enhancements to injections that allow you to return bindings based either by type, scope, existing bindings or all. The framework also extends the SPI for elements to expose elements introduced by third-party extensions. Additional enhancements include improved OSGi support, numerous servlet extensions, support for singletons, and Struts 2 integration. Other features include:

* Simpler stack traces when AOP is involved
* Duplicate bindings are ignored rather than throwing an exception.
* Repackaged cglib, asm & guava classes are now hidden from IDE auto-imports
* Support for Maven

Guice vs. Spring

As is often mentioned in discussion groups the Spring framework already supports dependency injection. The most often voiced concern is that developers must choose between Guice and Spring. While Guice offers an alternative to Spring’s DI methods, it does not supplant the Spring framework. The truth is that Guice can coexist with Spring, and can be used independently or in conjunction with Spring. For example, Guice supports AOP method interceptors, allowing developers to use Spring’s transaction interceptor. There is also a SpringIntegration() class that makes it possible to bind to Spring beans. What Guice brings to the table is type safety, exception handling, and simplicity by removing both an abstraction layer and the need for XML configuration.

In an InfoQ interview, Spring founder Rod Johnson talks about how the annotation-driven injection (annotation binding) in Spring 2.5 was inspired by Guice, and covers the fundamental differences in Spring 3.0’s @Configuration. There is also an updated comparison with Spring on Google Code.

MiniGuice

Finally it’s worth noting that the recent "Guice 4.1" that was announced in some fora was an April fools joke perpetrated by the Guice team. The announcement talked of a stripped-down "MiniGuice," suitable for very small applications. As Guice team member Sam Berlin put it, "Guice 4.1 is a radical rethinking of Guice, dependency injection, and how java libraries are shipped." Guice 4.1 consists of a single file and can be called from this simple API:

myApp program = MiniGuice.inject(myApp.class, new Module1(), new Module2());*

The Guice 4.1 source file can be found at Google Code.

 

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

"Guice 4.1" by Colin Decker

"Guice 4.1" was an April Fools' Day joke, by the way. "4.1" as in 4/1. =) MiniGuice is real of course.

Guice 4.1 by Stuart McCulloch

Interested readers might want to know that Guice 4.1 was announced on a memorable date (04/01) ... make of that what you will :)

PicoContainer by Aslak Hellesøy

I guess I'm tooting my own horn here (being one of the PicoContainer creators), but I still don't get why dependency injection needs annotations or config files.

PicoContainer may not have the sexiest web site, but it's still an incredibly simple DI container that's easy to use and gets the job done. Reflection-based annotation-less constructor based autowiring all the way. Here is a fairly recent StackOverflow thread that compares some DI containers: stackoverflow.com/questions/2026016/google-guic...

InteliiJ IDEA's plugin system uses PicoContainer - works pretty well.

That said, I rarely even use PicoContainer these days even though I'm coding Java all day.

I use the *new* keyword. Yep.

Re: I use the *new* keyword. Yep. by Thomas Anderson

That's it! DI is highly overrated! People 'wire together' applications using config files or annotations without real benefit. Quite the contrary. They introduce additional complexity to their programs because of DI. Why? Nobody knows. DI has become an end in itself without reason.

Re: I use the *new* keyword. Yep. by Stuart McCulloch

Hmm... when it comes to re-wiring electrics I still prefer labels to no labels at all, and the same goes with re-wiring components. Standard annotations like @Inject help document not only what a component depends on, but also how to to pass in those dependencies. This can be useful even when skipping DI and using 'new', as I don't have to guess how the component was supposed to be initialised. Also note you can still use a class with annotations without needing the extra jar - the JVM will just ignore annotations that aren't on the classpath.

www.slideshare.net/mcculls/redev-2010-guice-and...

Re: I use the *new* keyword. Yep. by Nilesh Thali

There are two planes of thought i'd like to present:
1. in the agile world, there's no need to add DI the first time you're writing your code. Simply introduce it when you have a real use case of having to switch the implementation (which IMHO is the real benefit of DI). personally, i have been on several projects where we have spring DI, but there has never been an alternate implementation of the objects being injected - in which case the *new* keyword would have done just fine.

2. unfortunately, i have found far too few developers who are brave enough to refactor - hence, once you tightly couple with the *new* keyword, the next guy that comes along and has to change the implementation will most likely write an "if" statement in the main code (not even add a factory).

Re: I use the *new* keyword. Yep. by bruce b

There are two implementations in the majority of cases: the production implementation and a test double (mock/stub/fake) implementation to facilitate automated testing scenarios. If the class is very lightweight and can be used as is in testing without complications, then using new inline is probably good enough. Otherwise, I can't imagine ever returning to the pre-DI days in Java. Note, I said "in Java". Clearly other languages exist that are more dynamic and flexible that make a DI framework unnecessary for the most part.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

7 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT