Dagger DI for Spring Refuges: 10 Tips

· ioc tips

I've been experimenting with Dagger, a dependency inject systems. I was drawn to it probably for the same reasons as others:

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:

  1. 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.
  2. 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.
  3. Like Spring et al, it can't detect parameterized classes, e.g. Set. You'll need to use @Named on these.</span></li>
  4. There's no in-built support for JNDI, but you can easily make some.
  5. 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.
  6. @Singleton on a class will be ignored if the object is specified by the module, you need to  annotate in the module too.
  7. Use @Singleton by default, then remove if not necessary.
  8. 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>
  9. If need to add any "dangling" dependencies to your root (you get a "unused @Provider" error).
  10. When debugging the graph, you can visualise the graph by looking at the ${moduleName}.dot files.
  11. </ol>

    Further reading: