Junior — Middle
What is the difference between @Component and @Subcomponent annotations in Dagger in the context of dependency injection?
sobes.tech AI
Answer from AI
In Dagger, the annotations @Component and @Subcomponent are used to define dependency graphs but serve different roles:
-
@Component — the main component that creates and provides dependencies. It is the root of the dependency graph and can include modules.
-
@Subcomponent — a child component that inherits dependencies from its parent component and can add its own. It is used for more fine-grained organization of the graph, for example, for scopes with shorter lifetimes.
Differences:
@Componentcreates an independent dependency graph.@Subcomponentdepends on the parent component and can use its dependencies.- A Subcomponent is declared inside a component or separately, but is linked to the parent through a method in the parent component.
Example:
@Component
interface AppComponent {
Subcomponent.Builder subcomponentBuilder();
}
@Subcomponent
interface Subcomponent {
@Subcomponent.Builder
interface Builder {
Subcomponent build();
}
}