Junior — Middle
How is Dagger configured and integrated into the project?
sobes.tech AI
Answer from AI
To set up and implement Dagger in an Android project, the typical steps are:
- Add dependencies: Include Dagger dependencies (
dagger,dagger-compiler) in yourbuild.gradle. - Create components: Define an interface with
@Componentannotation that connects modules and injection points. - Create modules: Classes with
@Moduleannotation provide methods with@Providesto specify how to create dependencies. - Inject dependencies: Use
@Injectannotation in target classes (Activities, Fragments, ViewModels) for fields or constructors. - Initialize component: Usually, create an instance of the component (e.g., in Application class) and perform injection.
Example:
// Module
@Module
class NetworkModule {
@Provides
Retrofit provideRetrofit() {
return new Retrofit.Builder()
.baseUrl("https://api.example.com")
.build();
}
}
// Component
@Component(modules = {NetworkModule.class})
interface AppComponent {
void inject(MainActivity activity);
}
// In Activity
public class MainActivity extends AppCompatActivity {
@Inject
Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApplication) getApplication()).getAppComponent().inject(this);
// Now retrofit is available for use
}
}
Thus, Dagger allows centralized dependency management, simplifying testing and maintenance of code.