Junior — Middle
What is the role of the @Provides annotation in the context of Dependency Injection and what is its purpose?
sobes.tech AI
Answer from AI
The @Provides annotation is used in Dependency Injection libraries (such as Dagger in Android) to denote methods that create and supply dependencies. These methods are usually located in modules (@Module) and are responsible for creating objects that will be injected into other parts of the application.
For example, if you have a class that depends on a certain service, you can write a method with @Provides that creates this service and allows the DI framework to automatically pass it where needed.
Example:
@Module
public class NetworkModule {
@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder()
.baseUrl("https://api.example.com")
.build();
}
}
Thus, @Provides explicitly indicates how to create dependencies that cannot be automatically created through constructors.