Junior — Middle
How is the object integrated into Dagger for dependency injection?
sobes.tech AI
Answer from AI
In Dagger, dependency injection occurs through annotations and code generation.
Main steps:
-
Defining a module (@Module) — a class that provides dependencies using methods annotated with
@Provides. -
Component (@Component) — an interface that connects modules and dependency injection sites.
-
Injection (@Inject) — fields or constructors where Dagger will supply dependencies.
Example of constructor injection:
class Engine {
@Inject
Engine() {}
}
class Car {
private final Engine engine;
@Inject
Car(Engine engine) {
this.engine = engine;
}
}
@Component
interface CarComponent {
Car getCar();
}
Here, Dagger will automatically create an Engine object and inject it into Car when creating it via CarComponent.
Thus, dependency injection in Dagger is performed through the @Inject annotation and is connected via components and modules.