轉載地址:http://fanxu.me/post/2015-10-29
Dagger2 是Google在Square的Dagger基礎上擴展的依賴注入組件,從Dagger1轉到Dagger2,會有一些不一致的地方,但總體來說,Dagger2較Dagger1優化了非常多。
本文就Dagger2 與Dagger1的不同做些簡述。 由于還沒有正式使用Dagger2,所述觀點可能有所偏頗,歡迎拍磚。
生成代碼
與一代不同,Dagger2會生成一堆輔助代碼,如下圖。
雖然犧牲了動態特性,但Dagger2的生成代碼使得其極易調試,閱讀和分析都非常方便。
Component
Dagger2新增了Component,作為Module和Inject對象之間的橋梁。
與Dagger1不同,Dagger2中所有的對象,必須要與明確的@Inject Contructor才會自動構建,否則必須按照Component進行注入。這樣做,雖然會少許有些不方便,但代碼的可讀性提高了很多,較容易理解。
Singleton
Dagger2支持Singleton屬性,支持在Provides方法和類頭部添加,其含義也是單例。
但必須在Component上也聲明為Singleton, 這個有點比較難以理解。
Scope
Dagger2添加了Scope特性,可以給定對象的存活區域,這個對于Android編程非常有利。
總結
總體來說,Dagger2 比較容易理解,生成的代碼也很方便。
其他內容等后續逐漸使用,再行補充。
自己搞了一個java的Demo,https://github.com/fanxu123/Dagger2Demo
Links
http://frogermcs.github.io/dependency-injection-with-dagger-2-introdution-to-di/
http://frogermcs.github.io/dependency-injection-with-dagger-2-the-api/
http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/
http://frogermcs.github.io/dagger-graph-creation-performance/