Dependency Injection with Play Framework and Google Guice

Guice is a lightweight dependency injection framework developed by Google and it’s a good alternative if you are looking for DI on your Play Framework-based application. Keep in mind that the framework is lightweight but you still need to evaluate your application specifically and decide what should be managed by Guice and what should not. It does add some overhead in terms of development time which is the plumming that Play! provides and we grew to love.

It’s very common for applications using DI, especially Spring-based ones, to overuse the DI framework by loading every bean/class imaginable into the context. By the way I don’t think this issue has anything to do with Spring itself, just developers mis-using the framework and Spring happens to be the most popular Java-based DI framework so the issue becomes more noticeable. That’s a sure recipe for a very heavy context, with a slow startup and all that jazz we should desperately try to avoid. I have just recently ran into an application loading a StringUtils type of class into a Spring context, I still don’t understand why. If you know certain parts of your application don’t need separate or different behaviors based on a certain context, you probably don’t need Dependency Injection.

Enough talk let’s get down to the implementation.

1) First add the Guice module to your application (dependencies.yml if you are using Play 1.2 or higher)

require: - play - play -> guice 1.2

2) Then define your module

public class MyModule extends AbstractModule { @Override protected void configure() { this.bind(MyBean.class).toProvider(ReallyCoolBean.class).in(Singleton.class); } }

3) Then create your Injector

public class ApplicationDependencies extends GuiceSupport { /** * Guice Application Injector * * @see play.modules.guice.GuiceSupport#configure() */ @Override protected Injector configure() { return Guice.createInjector(new MyModule()); } }

4) Now use @Inject wherever you want

@InjectSupport public class MyService { @Inject static MyBean myBean; }

And Voila! (Ok I still speak no French but I am trying here so give me props for the effort!)

Please visit Guice’s documentation to learn more about the framework but this is what you need to do to use it on your Play Framework application.

I have just found out my ex-boss David Baker who is currently a Google employee has done some work on the framework which I thought was very cool. I have just met him here in New York after 12 years, thank you David for showing me around, I had a great time!

And by the way checkout DI with Scala and the Cake Pattern, very cool! That’s a link to Jonas Boner’s blog, Mr. Akka, which is also a great framework but I am leaving that for another day.

Now Go Play!