Mobile Development 4 min read

Understanding Dagger 2 Modules, Components, and Subcomponents in Android

This article explains how Dagger 2 structures dependency injection for Android apps using Modules, Components, and Subcomponents, illustrating their roles with diagrams, comparing them to manual injection, and showing how they clarify code dependencies while keeping runtime overhead minimal.

Liulishuo Tech Team
Liulishuo Tech Team
Liulishuo Tech Team
Understanding Dagger 2 Modules, Components, and Subcomponents in Android

Dagger 2 is a lightweight Java dependency‑injection framework released by Google that performs injection at compile time, allowing Android applications to add DI with negligible performance cost. In the "雅思流利说" project, Dagger 2 made the code’s dependency graph explicit, effectively drawing a UML diagram of relationships.

The framework revolves around two main concepts: Modules and Components. A Module acts like a production line that provides a set of objects, possibly requiring upstream modules for inputs. It knows how to create instances but not who will consume them.

A Component functions as a factory; client code obtains required dependencies from it. The article shows example code where AppComponent supplies TLTokenInterceptor , RealmConfiguration , and a Retrofit instance, and visual diagrams illustrate the component’s structure.

Comparing Dagger 2 to manual injection, the UML diagram of a non‑Dagger setup demonstrates that while the underlying class dependencies remain unchanged, Dagger removes the need for client classes to manage injection details. Clients simply declare a method in the Component, and Dagger resolves the required objects from the registered modules.

The concept of Subcomponents is introduced to handle scoped dependencies, such as those needed only within a specific activity lifecycle. Using LoginRegisterActivityModule as an example, the article explains how this module depends on NetworkModule for a token interceptor, and how Subcomponents can be built via a Builder to inherit external dependencies.

Overall, Subcomponents make inter‑module relationships clearer and lay the groundwork for scopes, helping developers grasp the entire code base’s architecture after familiarizing themselves with the Component and Subcomponent hierarchy.

Mobile DevelopmentAndroiddependency injectionComponentsModulesDagger2Subcomponents
Liulishuo Tech Team
Written by

Liulishuo Tech Team

Help everyone become a global citizen!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.