Sobes.tech
Junior — Middle

How is the use of annotations in the Dagger library for dependency injection implemented?

sobes.tech AI

Answer from AI

In the Dagger library for dependency injection in Android, annotations are used to describe how to create and provide objects.

Main annotations:

  • @Inject — marks a constructor, field, or method where Dagger should inject the dependency.
  • @Module — a class that contains methods annotated with @Provides, describing how to create specific dependencies.
  • @Provides — annotates a method within a module that returns a dependency object.
  • @Component — an interface that connects modules and injection points, generating code to create the dependency graph.

Example usage:

@Module
class NetworkModule {
    @Provides
    OkHttpClient provideOkHttpClient() {
        return new OkHttpClient.Builder().build();
    }
}

@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 the client is initialized by Dagger
    }
}

Thus, annotations allow Dagger to automatically generate code for creating and passing dependencies, simplifying their management.

How is the use of annotations in the Dagger library… - sobes.tech