Dagger Dependency Injection in a Java Servlet

I couldn’t find a great example of using the Dagger dependency injection framework in a Java servlet, so I’m publishing some of the key bits of what I did in the hopes of saving others some hassle.

What’s Dagger? A lightweight dependency injection framework, from Square.  Particularly popular for Android projects, and implements standard JSR 330 annotations.  So easy to move up to Guice later if you need a reacher DI solution.

How? The general idea, following this Stack Overflow answer, is to use a ServletContextListener to initialize Dagger, build your object graph, and inject it into the ServletContext.  In the servlet’s init method, you can then use that graph. I’ve tried to provide a more precise outline of this in code below:

Details

If you’re using Eclipse, getting Dagger’s code generation working properly can also be a bit tricky.  The bit in this answer about the JARs to include under Project Settings -> Java Compiler -> Anotation Processing –> Factory Settings helped me.

2 thoughts on “Dagger Dependency Injection in a Java Servlet

  1. thank you very much for this awesome tutorial,
    for dagger 2 (the new version) will the code still the same

    • I think it will work, but there’s likely a cleaner approach: 1) annotate each dependency with `@Inject` (javax.inject.Inject); 2) in `BaseServlet.init()`, call `this.objectGraph.inject(this)`. This avoids need for `this.dependency = this.get(Dependency.class);` for each dependency class.

Make a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s