Junior — Middle
Explain the purpose of the @Provides annotation in the context of dependency injection.
sobes.tech AI
Answer from AI
The @Provides annotation is used in dependency injection libraries (such as Dagger) to denote methods that create and supply dependencies.
When you cannot simply inject an object through the constructor (for example, if object creation is complex or requires additional logic), you create a method with @Provides that returns the required object. The DI framework calls this method to obtain an instance of the dependency.
Example in Dagger:
@Module
class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.build();
}
}
Here, the method provideOkHttpClient creates and returns a configured OkHttpClient object. The DI container uses this method to inject OkHttpClient where needed.
Thus, @Provides helps manage the creation of dependencies with custom logic within the DI system.