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:
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.