简体   繁体   中英

Java dependency injection: Dagger 1 vs Dagger 2, which is better?

What are the advantages of Dagger 2 over Dagger 1 ?

So far I found (just) 2:

  • Dagger 2 allows you to use code obfuscation with proguard
  • Dagger 2 is faster (which is not much of an advantage when using it for android application but it is sure an important thing if you use it for some kind of server)

In the same time I found one big disadvantage: you cannot have module overrides ( @Module(overrides = true) ) in Dagger 2, which is largely annoying at least for me - it was very useful for unit test.

Are there other advantages / disadvantages?

Some advantages and disadvantages taken from https://blog.gouline.net/2015/05/04/dagger-2-even-sharper-less-square/ and http://google.github.io/dagger/dagger-1-migration.html :

Advantages of Dagger 2:

  • No more reflection - everything is done as concrete calls (ProGuard works with no configuration at all)
  • No more runtime graph composition - improves performance, including the per-request cases
  • Traceable - better generated code and no reflection help make the code readable and easy to follow
  • Supports method injection in addition to field and constructor injection which were the only two types supported by Dagger 1
  • Modules require less configuration than Dagger 1
  • Allows users to use any well-formed scope annotation. Dagger 1 only supported a single scope: @Singleton .

And disadvantages:

  • The inject() method now has a strong type association with the injection target. This is good for debugging, but it complicates a common practice of injecting from base classes (eg base activities, fragments etc).
  • Component implementation requires rebuilding the project to appear and any injection-related compile errors result in the class disappearing (ie not being generated).
  • Doesn't support overrides . Modules that override for simple testing fakes can create a subclass of the module to emulate that behavior. Modules that use overrides and rely on dependency injection should be decomposed so that the overriden modules are instead represented as a choice between two modules.

EDIT 2016/11/16: This is not a technical advantage, but Dagger 1 is now deprecated (as of September 15, 2016) and will no longer be actively developed. They recommend migrating to Dagger 2.

I wouldn't recommend having a look at toothpick .

As a co-author, I am obviously over biased, but yeah this one is far simpler to use, at least as fast in most cases than the daggers. And really the scope tree is a very very powerful way to develop more advanced features like recycling instances in scopes spanning on multiple activities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM