经过一段时间的纠结和水深火热,终于渐渐领悟了Dagger2,在此分享一下学习心得,希望同样对Dagger2水深火热的你们有点帮助。
接下来会分享一系列Dagger2内容。
@Singleton
@Component(modules = {AppModule.class, RetrofitModule.class})
public interface AppComponent {
IRetrofitRequest request();
Context getContext();
}
这里用@Component标注的AppComponent接口,提供了两个方法,一个返回的是IRetrofitRequest,一个是Context。 但是这两个对象在哪里实例化呢?
编译代码:Dagger2会自动生成一个叫DaggerAppComponent的类,该类会根据@Component(modules = {AppModule.class, RetrofitModule.class}),这里的AppModule和RetrofitModule两个类中去寻找IRetrofitRequest和Context实例化的对象。如下介绍@Module
@Module
public class AppModule {
private Context context;
public AppModule(Context context) {
this.context = context;
}
@Provides//注意需要加上@Provides
public Context getContext() {
return context;
}
}
@Module
public class RetrofitModule {
@Provides//提供对象,必须添加该注解
@Singleton//单例模式,这里的IRetrofitRequest 是全局的对象,接口调用的时候需要用到该类(自定义)
public IRetrofitRequest getService() {
//打印拦截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)//添加打印拦截器
.connectTimeout(30, TimeUnit.SECONDS)//设置请求超时时间
.retryOnConnectionFailure(true)//设置出现错误进行重新连接。
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConst.URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build();
return retrofit.create(IRetrofitRequest.class);
}
}
这里需要注意的是提供实例化对象的方法上需要添加@Provides注解
public class A {
@Inject
B b;//需要被实例化的对象
}
public class B {
@Inject//提供对象的实例化构造函数
public B() {
}
@Inject//当构造函数被执行之后,立马执行改方法
public void setPresenter(){
xxx;
}
}
Dagger2会自动生成很多类文件,其中一个就是DaggerXXX,这里的XXX就是用@Component标注的接口名,比如生成了DaggerAppComponent类文件,该类文件实现了AppComponent接口,并且根据相关的@Module提供的实例进行初始化。
public class App extends Application {
private static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(getApplicationContext()))//AppComponent关联的AppModule类
.retrofitModule(new RetrofitModule()) //AppComponent关联的RetrofitModule类
.build();
}
public static AppComponent getComponent() {
return appComponent;
}
}