Junior — Middle
How can automatic dependency injection be configured when using Dagger?
sobes.tech AI
Answer from AI
To set up automatic dependency injection in Dagger, you need to use the @Inject annotations and @Component interfaces.
-
In the constructor of the class that should receive dependencies, the
@Injectannotation is placed. -
An interface with the
@Componentannotation is created, which links dependency providers (modules) and the classes into which they will be injected. -
In the class where injection is needed, the component's
inject(this)method is called, which automatically injects all dependencies marked with@Inject.
Example:
class Engine {
@Inject
Engine() {}
}
class Car {
@Inject
Engine engine;
@Inject
Car() {}
}
@Component
interface CarComponent {
void inject(MainActivity activity);
}
// In MainActivity
CarComponent component = DaggerCarComponent.create();
component.inject(this); // dependencies will be injected automatically
Thus, Dagger generates code that automatically creates and injects dependencies if annotations and components are used correctly.