一個Android和java快速依賴注射器。java
Dagger 2是依賴注入的編譯時進化方法。 採用Dagger 1.x開始的方法達成最終結論,Dagger 2.x消除了全部的反射,並經過刪除傳統的ObjectGraph / Injector來改善代碼清晰度,有利於用戶指定的@Component接口。android
這個github項目表明瞭Dagger 2開發流。 較早的項目頁面(Square,Inc的存儲庫)表明較早的1.0開發流。 這兩個版本都受益於Square,Google和其餘貢獻者的強烈參與。git
Dagger 2目前正在積極發展,主要是內部在 Google,按期推進開源社區。 快照版本將自動部署到sonatype的中央maven存儲庫,每一個乾淨的版本與版本HEAD-SNAPSHOT。github
官網原文:
Dagger 2 is a compile-time evolution approach to dependency injection. Taking the approach started in Dagger 1.x to its ultimate conclusion, Dagger 2.x eliminates all reflection, and improves code clarity by removing the traditional ObjectGraph/Injector in favor of user-specified @Component interfaces.apiThis github project represents the Dagger 2 development stream. The earlier project page (Square, Inc's repository) represents the earlier 1.0 development stream. Both versions have benefitted from strong involvement from Square, Google, and other contributors.bash
Dagger is currently in active development, primarily internally at Google, with regular pushes to the open-source community. Snapshot releases are auto-deployed to sonatype's central maven repository on every clean build with the version HEAD-SNAPSHOT.服務器
依賴注入框架已經存在多年,具備用於配置和注入的各類API。那麼,爲何要從新發明輪?Dagger 2是第一個用生成的代碼實現完整堆棧的。指導原則是生成模仿用戶可能手寫的代碼的代碼,以確保依賴注入是能夠簡單,可追溯和執行的。網絡
官網原文:
Dependency injection frameworks have existed for years with a whole variety of APIs for configuring and injecting. So, why reinvent the wheel? Dagger 2 is the first to implement the full stack with generated code. The guiding principle is to generate code that mimics the code that a user might have hand-written to ensure that dependency injection is as simple.app
由於如今android studio 3.0在測試,基本上都是使用as 2.3.3就無需再加入插件了,直接在app → build.gradle → dependencies 中加入依賴就能夠開始使用了。框架
compile 'com.google.dagger:dagger:2.x'
annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
x是版本號,目前最新的是2.11,查看最新版
用於告訴Dagger2,咱們須要這個類的實例對象。主要用於標記哪一個類是須要注入的,可標註在對象或方法上,不能標記private修飾的。
用於對外提供對象,通常可在@Module標註的類中添加自定義方法,方法標註@Provides,方法體中可用來作一些實例化操做等。
配合@Module一塊兒使用,@Provides用於標記方法,表示能夠經過這個方法獲取一個對象,通常用於自定義類中。
主要用於關聯@Module標註的類和Activity及Fragment的子類。
用於區別不一樣對象的實例,必需要成對出現。@Named是以本身定義的字符串去識別,@Qualifier是以註解類(@interface)去識別。
dagger 2中的單例模式,@Module類中使用了,@Component中也要使用。
Scopes但是很是的有用,Dagger2能夠經過自定義註解限定註解做用域。這個註解我也不太熟悉,具體能夠參考網絡或官網。
先拿一個簡單的網絡請求依賴注入。
整個包的結構最重要的就是 di 包下兩個,network 包下是封裝的一個簡單的 retrofit 2.0 網絡請求
爲了快速的看懂module和component中的代碼,咱們先看看network包下的代碼,上代碼
貼心代碼
------ApiService.class------
@GET("data/{type}/{count}/{page}")
Observable<ResponseBody> getGank(@Path("type") String type,
@Path("count") int count,
@Path("page") int page);
}
------RetrofitClient.class------
/**
* 請求超時時間
*/
private static final long DEFAULT_TIMEOUT = 10 * 1000;
/**
* 服務器地址url
*/
private static final String BASE_URL = "http://gank.io/api/";
private static ApiService sApiService;
public static ApiService getDefault() {
if (null == sApiService) {
synchronized (RetrofitClient.class) {
if (null == sApiService) {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()
//設置超時時間
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
sApiService = new Retrofit.Builder()
.client(httpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build().create(ApiService.class);
}
}
}
return sApiService;
}複製代碼
好了,一個超普通的 retrofit 請求封裝。下面再看看 NetworkModule.class
想必看也看得懂吧,一個類被標記 @Module 提供一個@Provides標記的方法,providesApiService()用於返回一個retrofit實例。代碼就不貼出來了,多敲敲就會了 (=^ ^=)
再來看看NetworkComponent.class,他至關因而一個鏈接器,鏈接activity子類和module
注意:inject()中參數不能寫Activity,不然會報空指針。
立刻就快完成了,在 MainActivity.class 中注入
對象 ApiService 經過 @Inject 注入,DaggerNetworkComponent 是由系統生成的(as菜單欄 → Build → Rebuild Project),若是找不到 DaggerNetworkComponent 就是你寫錯了,具體看log信息。
結尾:
在@Component中有一個dependencies,能夠理解爲依賴。過幾天我會寫一個dagger2在mvp中應用的博客,會把dagger的基礎使用都寫上,謝謝你們 (=^ ^=)