@Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { void inject(MyApplication application); } @Module public class ApplicationModule { private final MyApplication application; public ApplicationModule(MyApplication application) { this.application = application; } @Provides @Singleton Context provideApplicationContext() { return application; } @Provides @Singleton ApiService provideApiService() { return new ApiService(); } } @Module public class NetworkModule { @Provides @Singleton OkHttpClient provideOkHttpClient() { return new OkHttpClient(); } @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl("https://example.com") .client(okHttpClient) .build(); } @Provides @Singleton ApiService provideApiService(Retrofit retrofit) { return retrofit.create(ApiService.class); } } public class MyApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .networkModule(new NetworkModule()) .build(); applicationComponent.inject(this); } public ApplicationComponent getApplicationComponent() { return applicationComponent; } }


上一篇:
下一篇:
切换中文