Dagger DI for Spring Refuges: 10 Tips
I've been experimenting with Dagger, a dependency inject systems. I was drawn to it probably for the same reasons as others:
- Compile time checking.
- Very small (<100kb), vs Guice (~500kb) and Spring (~800kb).
- Fast.
I've been migrating a toy app from Spring, an app which uses Spring to create a context which internally sends JMS messages around. The app is a bit JEE, whereas I think Dagger is aimed at Android.
What I found:
- Dagger doesn't really like exceptions, either thrown from a module method, or from an constructor. I ended up creating a fair amount of code to wrap them in RTEs.
- Dagger doesn't provide support for bean life-cycle management, or hooks e.g. @PostConstruct. I ended up writing a solution to this, but it's poorly designed and doesn't have the compile time benefits.
- Like Spring et al, it can't detect parameterized classes, e.g. Set
. You'll need to use @Named on these.</span></li> - There's no in-built support for JNDI, but you can easily make some.
- You must either annotate the constructor with @Inject, or add the object to your module. If you have a no-args constructor, and you don't build it in the module, you'll need to create one.
- @Singleton on a class will be ignored if the object is specified by the module, you need to annotate in the module too.
- Use @Singleton by default, then remove if not necessary.
- Dagger only has two scopes: singleton and non-singleton. Request and session are not supported. Using Provider
gives the same effect as prototype.</span></li> - If need to add any "dangling" dependencies to your root (you get a "unused @Provider" error).
- When debugging the graph, you can visualise the graph by looking at the ${moduleName}.dot files.
</ol>Further reading: