I have a question regarding Android Dagger 2 and the use of @Inject and @Provide annotations. The following are two simplified examples:
public class A { String msg; public A(String msg){ this.msg = msg; } } public class B { public A a; public B(A a){ this.a = a; } } @Module public class AModule { @Provides A providesA(){ return new A("blah"); } @Provides B ProvidesB(A a) { return new B(a); } }
The example is pretty straight forward, I have two methods in my AModule with @Provides annotations. Therefore, the dagger can create object B using instance A with the string "blah".
My second example is as follows:
public class A { String msg; public A(String msg){ this.msg = msg; } } public class B { public A a; @Inject public B(A a){ this.a = a; } } @Module public class AModule { @Provides A providesA(){ return new A("blah"); } }
In this example, Dagger can create an instance of B because object A can be created using the AModule. Instance B can be created because its constructor uses the @Inject annotation.
So my question is: what is the difference between these two examples. Both seem to have the same semantics. The generated code is different and are there any pitfalls? Or is it just a question or personal taste or best practices?
source share