【发布时间】:2018-08-18 21:27:21
【问题描述】:
诚然,Dagger 很难,我正在尝试注入 Retrofit。我注入了 Context 和 SharedPreferences,它运行良好。但 Retrofit 打破了这一切。 它识别 DaggerRetrofitComponent 类,但没有找到 DaggerAppComponent。
改造模块:
@Module
public class RetrofitModule {
public static final String BASE_URL = "http://api.themoviedb.org/3/";
@Provides
HttpLoggingInterceptor getHttpLoggingInterceptor(){
return new HttpLoggingInterceptor();
}
@Provides
OkHttpClient getOkHttpClient(HttpLoggingInterceptor interceptor){
return new OkHttpClient.Builder().addInterceptor(interceptor).build();
}
@Provides
GsonConverterFactory getGsonConverterFactory(){
return GsonConverterFactory.create();
}
@Provides
Retrofit getRetrofit(GsonConverterFactory gsonConverterFactory, OkHttpClient client){
return new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(gsonConverterFactory)
.client(client).build();
}
}
应用:
public class MyApplication extends Application {
private static AppComponent appComponent;
public static AppComponent getAppComponent(){
return appComponent;
}
@Override
public void onCreate() {
super.onCreate();
appComponent=buildComponent();
}
protected AppComponent buildComponent(){
if(BuildConfig.DEBUG){
Timber.plant(new Timber.DebugTree());
}
return DaggerAppComponent.builder().sharedPreferenceModule(new SharedPreferenceModule()).contextModule(new ContextModule(this)).build();
}
}
应用组件:
@Singleton
@Component(modules = {ContextModule.class, SharedPreferenceModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
}
改造组件:
@Singleton
@Component(modules = {RetrofitModule.class})
public interface RetrofitComponent {
void injectRetrofit(Activity activity);
//
}
主活动:
public class MainActivity extends AppCompatActivity {
@Inject
Context context;
@Inject
SharedPreferences sharedPreferences;
@Inject
Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerRetrofitComponent.builder().retrofitModule(new RetrofitModule()).build().injectRetrofit(this);
MyApplication.getAppComponent().inject(this);
}
}
【问题讨论】:
标签: android dependency-injection retrofit2 dagger-2