Guice Productivity
May 8, 2008
Plugin hell: we’ve all been there. Large frameworks like Spring, Seam, … often require IDE plugins for you to be productive. That’s cool. But installing plugins and getting them to work right, at least when using Eclipse, is utter, utter torture.
Some of them don’t work as advertised. Some of them don’t work with your particular Eclipse version. Some of them make others crash.
What’s refreshing about a framework like Guice is that you don’t need all of that. Because Guice is an all-Java framework, you don’t need to install any IDE plugins. Your Java IDE _is_ the plugin. There’s years and years of hard work at your fingertips, so why not work _with_ it instead of working against it? Developing with Guice feels like coming home.
Recently I cooked up a screen cast that shows off Multibindings, a much anticipated Guice 2.0 feature. As I mention in the beginning, I use some IDE templates for my Guice development, and you’ll probably agree with me that it shows. I’ll share those with you in a minute. But first, my brain fart of the day: Know and learn your IDE, and expect the same from the frameworks you use. 70% of the code generation refactorings/templates in my Multibindings screencast are built right into the IDE. And 100% of them are configurable out of the box.

Here’s what I’ve currently set up. This configuration is Eclipse specific, but I’m sure IDEA and others have similar features.
- Static imports: Window => Preferences => Java => Editor => Content Assist => Favorites.
- This thing is pure gold. It allows you to specify types that have static methods on them, so that Eclipse can index them and suggest static imports for methods you often use. This feature is an awesome time saver for things like Google Collections, but also for JUnit tests and not surprisingly Guice. For Guice I’ve added the
Matchersclass (AOP) and theNamesclass (eeeviiiil).
- This thing is pure gold. It allows you to specify types that have static methods on them, so that Eclipse can index them and suggest static imports for methods you often use. This feature is an awesome time saver for things like Google Collections, but also for JUnit tests and not surprisingly Guice. For Guice I’ve added the
- Templates: Window => Preferences => Java => Editor => Templates. Using this simple IDE feature, all boilerplate is just a
CTRL+SPACEaway. Important: press save (CTRL+S) and Organize Imports (CTRL+SHIFT+O) after you complete a template. This makes sure that you have all the needed import statements. - Binding Annotations: creating these is tedious and error prone. One approach is to copy-paste the boilerplate, the other is to have a template. I’ve set one up that automatically inserts the annotation headers you’d usually want.
Injectorcreation: I tend to run a lot of “experiments”, also known as the “Launching Main893.java” syndrome. So next to the binding annotation header, I’ve also set up a template that creates me an Injector with an inlineAbstractModule. Also works great for demos.- Constructor generation: simple template that creates the default constructor and puts your cursor in between the parenthesis so you can immediately start typing.

Other notable built-in features are CTRL+1 (Quick Fix) on constructor fields, which can create private final instance variables for selected constructor arguments, and typing a method name and hitting CTRL+SPACE to override or implement that method.
Now without further ado, here are some of my templates.
Mapped to ‘gah’ (as in Guice Annotation Header):
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotationMapped to ‘gin’ (as in Guice INjector and booze):
Injector i = Guice.createInjector(new AbstractModule() { protected void configure() { ${cursor} } });Mapped to ‘constr’ (creates a constructor and sets the cursor where it needs to be):
public ${enclosing_type}(${cursor}) { }
Enjoy!
Guice Book Released!
March 28, 2008
I should really get some sleep, but I can’t wait to get the word out. The book I was working on “Google Guice: Agile Lightweight Dependency Injection Framework” has gone live! It’s available in ebook and print-on-demand formats.
Apart from the title, I think the book reflects the fact that I’m a no-nonsense guy. I’m just like you, interested in new technology and I want to see this Guice thing in action. They did that with dependency injection? Hell yes; let’s see why they did it, and who they killed to get there (just kidding :-)).
So, months later I look on Amazon, and see this:

You can get my humble work together with the best Java book ever. That alone was so worth it :-)
Thanks again to Apress, Bob, Dhanji and the Guice community: I couldn’t have done it without you.
Guice, Spring 2.5 and Finding Mistakes Early
March 15, 2008
Yesterday I gave a talk on Guice at the Profict Wintercamp! The goal of the event was to look at how Guice changes the Spring landscape by letting both sides present their framework. From the Guice side there was me (thanks Bob, for not being able to come! ;-)), from the Spring side there was Alef Arendsen.
Surprisingly, there was only one Guice user present! They should have given us an “I went to the Profict Wintercamp and I lived.” t-shirt. :-) No seriously, I had a great time and enjoyed talking to other developers and the guys from SpringSource. Let’s hope I convinced some people to take a look at Guice!
Right before the talk I had some time to spare, so I quickly threw together a Guice demo application that I then re-implemented using the Spring 2.5 new annotation-driven configuration options. Next, I decided to take a look at how Spring compares with Guice in terms of error detection and error handling. This has always been one of Guice’s strengths, but it’s also one of those “nice-to-haves”. It’s like a cell phone. You don’t miss it until you have one. All those Spring users don’t know what they are missing!
The example code can be found here, and the error handling comparison can be found here. I’ll upload the presentation and the packaged source code soon. Enjoy!
Guice Book
December 13, 2007
I’m writing a book on Google Guice, the notorious DI framework created by Bob Lee. I’ve been active in the Guice community for quite a while now, and I have to say that it’s an honor to get the opportunity to write about one of the most innovative Java frameworks out there. Now that it’s been published on Amazon, I feel like I’ve reached the point of no return. The world knows, so I’d damn well better make sure that I deliver some quality. So far I’m having a blast, so perhaps I’m still in Ted’s phase two. :-)
On a related note, I enjoyed talking to Bob at Javapolis today. On popular demand he took the advanced route for his Guice talk, which I think was appropriate. Too bad he didn’t have enough time to go through the example though. I was pleased to learn that much of what he talked about already made it into the book, in some form. Which must be a good thing, right? Anyway, one more day at Javapolis, and then back to work. :-)
Wish me luck. I’ll try to make sure I won’t need it. ;-)
Guice Debug Output
December 8, 2007
Guice has a dirty little secret: it logs timing information to its JDK Logger. A while ago I created a simple utility class for myself to enable or disable the logging of Guice’s debug output to the console. Here goes nothing.
/**
* Enable or disable Guice debug output
* on the console.
*/
public class GuiceDebug {
private static final Handler HANDLER;
static {
HANDLER = new StreamHandler(System.out, new Formatter() {
public String format(LogRecord record) {
return String.format("[Guice %s] %s%n",
record.getLevel().getName(),
record.getMessage());
}
});
HANDLER.setLevel(Level.ALL);
}
private GuiceDebug() {}
public static Logger getLogger() {
return Logger.getLogger("com.google.inject");
}
public static void enable() {
Logger guiceLogger = getLogger();
guiceLogger.addHandler(GuiceDebug.HANDLER);
guiceLogger.setLevel(Level.ALL);
}
public static void disable() {
Logger guiceLogger = getLogger();
guiceLogger.setLevel(Level.OFF);
guiceLogger.removeHandler(GuiceDebug.HANDLER);
}
}
Output looks something like:
[Guice FINE] Configuration: 51ms [Guice FINE] Binding creation: 53ms [Guice FINE] Binding indexing: 0ms [Guice FINE] Validation: 131ms [Guice FINE] Static validation: 0ms [Guice FINE] Static member injection: 2ms [Guice FINE] Instance injection: 2ms [Guice FINE] Preloading: 1ms
Listen to the Logger, it’s making sense. Guice is fine! :-)
Builder Pattern Deluxe
July 12, 2007
Update: code available at http://code.google.com/p/garbagecollected/
Yesterday evening I came up with an interesting approach for implementing Josh Bloch’s revised GoF Builder pattern (warning: PDF). After some late night hacking, I can’t help but feel that this is very useful stuff. Take a look at Josh’s presentation first, and then take a look at this:
package builder;
public class SomeObject {
private final String mandatory;
private final int optional1;
private final char optional2;
private SomeObject (SomeObjectBuilder builder, String mandatory) {
this.mandatory = mandatory;
this.optional1 = builder.optional1();
this.optional2 = builder.optional2();
}
public interface SomeObjectBuilder extends Builder {
SomeObjectBuilder optional1(int optional1);
SomeObjectBuilder optional2(char optional2);
int optional1();
char optional2();
}
public static SomeObjectBuilder builder (final String mandatory) {
return BuilderFactory.make (SomeObjectBuilder.class,
new BuilderCallback () {
public SomeObject call (SomeObjectBuilder builder) throws Exception {
return new SomeObject(builder, mandatory);
}
});
}
public String toString() {
return new StringBuilder()
.append (getClass().getName())
.append (String.format ("[optional1=%s, ", optional1))
.append (String.format ("optional2=%s, ", optional2))
.append (String.format ("mandatory=%s]", mandatory)).toString();
}
public static void main(String[] args) {
System.out.println(SomeObject.builder("Mandatory!")
.optional1(35)
.optional2('A')
.build()
.toString()
);
}
}
Console output: SomeObject[optional1=35, optional2=A, mandatory=Mandatory!]
Using a dynamic proxy, the BuilderFactory provides the Builder<T> implementation for a given interface, so that you don’t have to write all that horrible boilerplate code. Often you use a builder when constructors get messy, but Builders with many parameters get messy too. Using this approach you not only save time, you also have the advantage of using a static factory method and having your specific builder as an interface instead of a concrete class. Full source code available upon request; feedback/suggestions/improvements appreciated!
Eat that, setter injection ;-)
Guice Thread Scope
June 7, 2007
UPDATE: The reset thing turned out to be a bad idea, I created simple Thread Scope instead. If you somehow seem to need a reset, consider this.
Ever wanted to use Guice‘s request scope outside of a web application? Try out my thread scope implementation and let me know what you think. Cast your vote if you want to see this scope added to Guice.
Here’s an example. Create a Module that looks like this:
Injector i = Guice.createInjector(new Module() {
public void configure(Binder binder) {
binder.bindScope(ThreadScoped.class, CustomScopes.THREAD);
binder.bind(ThreadCache.class).in(Scopes.SINGLETON);
// add your custom classes
binder.bind(SomeClass.class).in(CustomScopes.THREAD);
}
});
Each thread is automatically initialized for the scope. To reset it, use the ThreadCache:
@Inject private ThreadCache threadCache
public void someMethod() {
try {
// do stuff in thread scope
} finally {
threadCache.reset();
}
}
I’m thinking about loading this scope’s initialization code lazily (so that you’ll need to execute threadCache.start() or something like that). It currently doesn’t matter for me and the memory overhead is low anyway, but what do you think?
PS: only use field injection for examples ;-)
Scripting Guice
May 6, 2007
I really like Guice, a Java 5 style Dependency Injection framework by the bright guys at Google.
People who are used to Spring’s DI config often complain that they don’t like the “compiled configuration” thing (Java Modules) Guice has. In Spring, all your wiring is usually done in XML. So on one side you have compiled Java Guice Modules, a more natural programming model for Java developers, and on the other side you have XML configuration, nicely externalized. And yes, I know the Spring guys plan on having a Java version of their configuration syntax, but it looks just like the XML, so I don’t see any real advantages there.
Anyway, for the Spring users who want to try out Guice, you could externalize your configuration to a properties file, and load it from that. Or whatever format you’re willing to use. Heck, you could even write some code that parses a Spring config file and translates it into a Guice Module.
But here’s another idea: what about using a scripting language for all your object wiring needs? Why create a configuration file if you could use the highly readable Guice Binder syntax? Well, I tried it, and it works great :-)
Let’s start with an example. This one’s about me drinking some beer. So here’s me:
public class Robbie {
private Beer myBeer;
@Inject
public Robbie(@Strong Beer freshBeer) {
this.myBeer = freshBeer;
}
public void startDrinking() {
myBeer.drink();
}
}
And here’s some beer:
public interface Beer {
void drink();
}
public class Duvel implements Beer {
public void drink() {
System.out.println("Duvel!");
}
}
public class StellaArtois implements Beer {
public void drink() {
System.out.println("Stella Artois");
}
}
The @Strong annotation basically means I’d like a strong beer, not just some water with taste. So I created a Guice BindingAnnotation for that, and expressed the binding in a module:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Strong {}
public class BeerModule implements Module {
public void configure(Binder binder) {
binder.bind(Beer.class).to(StellaArtois.class);
binder.bind(Beer.class).annotatedWith(Strong.class).to(Duvel.class);
System.out.println("Configured using Java implemented Guice Module!");
}
}
So everyone is getting regular beers, unless they specify they want some stronger beer. You could run this code like this:
public class StartGuice {
public static void main(String[] args) {
Injector i = Guice.createInjector(Stage.DEVELOPMENT, new BeerModule());
Robbie robbie = i.getInstance(Robbie.class);
System.out.print("Robbie starts drinking: ");
robbie.startDrinking();
}
}
This prints:
Configured using Java implemented Guice Module!
Robbie starts drinking: Duvel!
Hmm… tasty. Now, let’s get us some scripting. I’ll thankfully use the new Java 6 scripting support, you could probably use the BSF as well. Also, I’ll use Jython for scripting, a Java Python implementation. So I throw in jython.jar, jython-engine.jar (from the scripting site), aopalliance.jar next to the guice.jar. By the way, if you want to know how all this scripting support stuff works, check out Jurgen’s excellent introduction.
Anyway, let’s try binding our dependencies in Python. Create a file called BeerBinder.py that looks like this:
import java
from scriptguice import *
def configure(binder):
binder.bind(Beer).to(StellaArtois);
binder.bind(Beer).annotatedWith(Strong).to(Duvel);
print "Configured Guice using Python method!"
Then we add some scripting magic to our Guice Module, so that we delegate the configure call to the Python script:
public class BeerModule implements Module {
public void configure(Binder binder) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine python = mgr.getEngineByName("python");
Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonmethod/BeerBinder.py");
try {
python.eval(reader);
Invocable invocablePython = (Invocable) python;
invocablePython.invokeFunction("configure", binder);
} catch (ScriptException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
If we run StartGuice again, the output now looks like:
Configured Guice using Python method!
Robbie starts drinking: Duvel!
Great, it works! Now let’s take it one step further and get rid of the ugly Java / Python mix. Python all the way! Create a file called BeerModule.py:
import java
from scriptguice import *
from com.google.inject import *
class BeerModule(Module):
def configure(self, binder):
binder.bind(Beer).to(StellaArtois);
binder.bind(Beer).annotatedWith(Strong).to(Duvel);
print "Configured using Python implemented Guice Module!"
# Factory method that returns new BeerModule
def getBeerModule():
return BeerModule()
So we created a class called BeerModule, and subclassed the Java class com.google.inject.Module. Jython really starts to shine here. Let’s do some magic to get the thing back in Java:
public class StartGuice {
public static Module getPythonBeerModule() {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine python = mgr.getEngineByName("python");
try {
Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonclass/BeerModule.py");
python.eval(reader);
Invocable invocablePython = (Invocable)python;
return (Module)invocablePython.invokeFunction("getBeerModule");
} catch (ScriptException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Injector i = Guice.createInjector(Stage.DEVELOPMENT, getPythonBeerModule());
Robbie robbie = i.getInstance(Robbie.class);
System.out.print("Robbie starts drinking: ");
robbie.startDrinking();
}
}
It’s been a long time since my last beer, so here we go:
Configured using Python implemented Guice Module!
Robbie starts drinking: Duvel!
Man, how cool is this? Now we have defined the entire Guice module in Python code, and I got drunk in the process. Life just doesn’t get any better, does it ;-)
Now you could take it even further and return an array of Modules or what not, which is probably what you want in a real world app. Oh and one final note: don’t just copy paste this code. Close the Reader and stuff. I’m just being lazy for the sake of the example.
Thanks to Bob Lee and Kevin Bourrillion for creating Guice, the coolest DI framework on the planet.
