Junior — Middle
What structure does the Dagger dependency injection tool have?
sobes.tech AI
Answer from AI
Dagger is a static dependency injection framework for Android and Java. Its structure is based on the following key components:
- @Module — a class that provides dependencies through methods annotated with
@Provides. - @Component — an interface that connects modules and injection points. The component generates code to create and provide objects.
- @Inject — an annotation used to indicate injection points (such as constructors, fields, or methods).
Example:
@Module
class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient();
}
}
@Component(modules = NetworkModule.class)
interface AppComponent {
void inject(MainActivity activity);
}
public class MainActivity extends AppCompatActivity {
@Inject
OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerAppComponent.create().inject(this);
// Now client is initialized by Dagger
}
}
Thus, Dagger builds a dependency graph at compile time, which improves performance and code safety.