Junior — Middle
Explain the principle of operation and structure of the Dagger dependency injection library.
sobes.tech AI
Answer from AI
Dagger is a dependency injection (DI) library for Android and Java applications. It allows automatic provision of required objects (dependencies) into classes, reducing coupling and simplifying testing.
Principle of operation:
- Dagger uses annotations to describe dependencies.
- During compilation, code is generated to create and connect objects.
- This ensures high performance and no reflection at runtime.
Main components:
@Module— a class that provides dependencies via methods annotated with@Provides.@Component— an interface that connects modules and injection points, creating a dependency graph.@Inject— an annotation indicating where to inject dependencies (e.g., in constructor or field).
Example:
@Module
class NetworkModule {
@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder()
.baseUrl("https://api.example.com")
.build();
}
}
@Component(modules = NetworkModule.class)
interface AppComponent {
void inject(MainActivity activity);
}
public class MainActivity extends AppCompatActivity {
@Inject
Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerAppComponent.create().inject(this);
// Now retrofit is ready to use
}
}
Thus, Dagger helps manage dependencies centrally and efficiently, improving application architecture.