Constructor Injection
suggest changeDagger can construct a class that has no dependencies when that constructor is annotated with @Inject.
public class Engine {
@Inject // <-- Annotate your constructor.
public Engine() {
}
}
This class can be provided by any component. It has no dependencies itself and is not scoped. There is no further code necessary.
Dependencies are declared as parameters in the constructor. Dagger will call the constructor and supply the dependencies, as long as those dependencies can be provided.
public class Car {
private Engine engine;
@Inject
public Car(Engine engine) {
this.engine = engine;
}
}
A component can provide Car only when it can also provide every constructor argument, Engine in this case. Engine is constructor-injected, so any component can provide a Car.
You can use constructor injection whenever all of the dependencies can be provided by the component. A component can provide a dependency, if
- it can create it by using constructor injection
- a module of the component can provide it
- it can be provided by the parent component (if it is a
@Subcomponent) - it can use an object exposed by a component it depends on (component dependencies)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents