經過一段時間的糾結和水深火熱,終於漸漸領悟了Dagger2,在此分享一下學習心得,希望同樣對Dagger2水深火熱的你們有點幫助。
接下來會分享一系列Dagger2內容。
Dagger2中常用的註解名詞以及含義
- @Component :用於註解一個interface, 比如:
@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:給添加了@Component註解的interface類提供實例化對象的類,比如:
@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註解
- @Provides:在標有@Module註解類的內部方法上,提供對象實例。
- @Singleton:單例-Dagger2幫我們實現的一個@Scope作用域。
-@Inject:需要用@Inject註解的地方主要有3,如下
- 用於標註需要被實例化的對象
- 提供實例化對象的構造函數
- 當類被實例化對象之後,需要馬上執行的方法
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; } }