Dagger 2: When to use constructor injections and when to use field injections?

后端 未结 1 1783
醉梦人生
醉梦人生 2021-02-05 05:19

I was kind of lazy and used to use almost entirely field injections. I was just providing empty constructor, put my @Inject fields I everything was looking nice and simple. Howe

相关标签:
1条回答
  • 2021-02-05 05:33

    Use constructor injection. if you can't, use property injection.

    Rule 1 seems ok, like decorations or attributes you can use Property(field) injection.

    Rule 2 seems ok, because who uses your class they have to follow your constructor. They may not know they have to intilaize your property also.

    Rule 3 It's not just good for unit test. It's good for applying Single Responsibilty. It's easier to see your object graph.Otherwise you will hide it with property.

    If we come in your question, yes there a lot of parameters in your constructor. But the solution is not property injection. You can refactor your code and use aggregate services

    0 讨论(0)
提交回复
热议问题