Android Dagger 2: Inject and provides

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?

+5
source share
1 answer

They work similarly, and the @Inject style is preferred when you have such a simple choice as in your example. However, this is not always the case:

  • If B, which A consumes, is not under your control and not DI-aware, you will not be able to add the @Inject annotation.
  • If B is an interface, you will need @Provides (or @Binds in newer versions of the dagger) to determine which implementation to use.
  • If you do not use a Dagger graphic object for each parameter entered, you can manually call the constructor whether it is marked as @Inject or not. This may be the case if you want a particular instance or constant to be a constructor parameter, but you cannot or do not want to configure the binding for the entire graph of objects.
  • If you want your binding to return null sometimes or otherwise choose between implementations, this logic can live in the @Provides method.
+7
source

All Articles