Hi I have a very simple dagger questions for android.
class Fooz {
@Inject Foo1 mFoo1;
public Fooz() {
....
}
}
class Fooz {
private Foo1 mFoo1;
@Inject public Fooz(Foo1 foo1) {
mFoo1 = foo1;
}
}
How are the two classes identical? The first one injects Foo1 field directly while the second one assignes mFoo1 in the constructor. For the second one, does Foo1 get injected from object graph as soon as Fooz is created and added to object graph? If they are different, why so? Thanks!
Constructor injection gives you more control over the object instantiation since using field injections means to restrict your class creation to reflection and rely on support to these particular injection annotations. Besides that, having the dependencies clearly on the constructor let the code easier to maintain and to test.
As far as I know, there is no difference regarding the way it is held on the dagger graph but a constructor call is always faster than injected fields.
In my opinion, we should use property only when we do not have control over the object creation, as in Activities
and Fragments
, per example.