A dagger is a way of connecting diagrams of objects and their dependencies. As an alternative to directly calling constructors, you get instances by requesting them from the dagger, or by providing the object that you would like to input using the instances created by Dagger.
Let me make a coffee house, which depends on Provider<Coffee> and CashRegister. Suppose you are connected to a module (possibly to LightRoastCoffee and DefaultCashRegister implementations).
public class CoffeeShop { private final Provider<Coffee> coffeeProvider; private final CashRegister register; @Inject public CoffeeShop(Provider<Coffee> coffeeProvider, CashRegister register) { this.coffeeProvider = coffeeProvider; this.register = register; } public void serve(Person person) { cashRegister.takeMoneyFrom(person); person.accept(coffeeProvider.get()); } }
Now you need to get an instance of this CoffeeShop, but it only has a two-parameter constructor with its dependencies. So how do you do this? Simple: you tell the dagger to make the factory method available on the instance of the component that it generates.
@Component(modules = {}) public interface CoffeeShopComponent { CoffeeShop getCoffeeShop(); void inject(CoffeeService serviceToInject);
When you call getCoffeeShop , Dagger creates a Provider<Coffee> for the LightRoastCoffee delivery, creates a DefaultCashRegister, puts them into the Coffeeshop constructor, and returns the result. Congratulations, you are the proud owner of a fully equipped coffee shop.
Now all this is an alternative to void injection methods, which take an already created instance and inject it into it:
public class CoffeeService extends SomeFrameworkService { @Inject CoffeeShop coffeeShop; @Override public void initialize() {
So, you have it: two different styles, both of which give you access to completely injected graphs of objects, without listing or caring about which dependencies they need. You may prefer one method or another or prefer factory methods for top-level injections and members for Android or utility applications or any other type of mix and match.
( Note. In addition to using them as entry points into the object graph, no-arg attributes, known as collateral methods, are also useful for displaying bindings for component dependencies, as described in David Rawson in another answer .)