Dagger2:Scope, Component間依賴和subComponent

在上一篇文章(http://www.lxweimin.com/p/f56d5b7e8b4d)中,我們接觸到了Dagger2的基本用法。然而在實際Android開發(fā)當(dāng)中,還會有更進一步的需求:需要有多個不同生命周期的多個Component,例如,有些依賴圖是全局單例的,而有些依賴圖會與Activity/Fragment同周期,或者有些依賴圖是要與用戶登錄同周期。在這些情況下,我們就需要自定義Scope來維護多個Component各自依賴圖的生命周期。更進一步的,我們討論利用Component間的依賴和subComponent兩種方法來創(chuàng)建多個Component。

1. Scope

Scope注解是JSR-330標(biāo)準(zhǔn)中的,該注解是用來修飾其他注解的。 前篇文章提到的@Singleton就是一個被Scope標(biāo)注的注解,是Scope的一個默認實現(xiàn)。
Scope的注解的作用,是在一個Component的作用域中,依賴為單例的。也就是說同一個Component對象向各個類中注入依賴時候,注入的是同一個對象,而并非每次都new一個對象。
在這里,我們再介紹自定義的Scope注解,如:

@Scope
public @interface ActivityScope {
}

如上,ActivityScope就是一個我們自己定義的Scope注解,其使用方式與上篇文章中我們用Singleton的用法類似的。顧名思義,在實際應(yīng)用中Singleton代表了全局的單例,而我們定義ActivityScope代表了在Activity生命周期中相關(guān)依賴是單例的。
Scope的注解具體用法如下:
(1). 首先用其修飾Component
(2). 如果依賴由Module的Provides或Binds方法提供,且該依賴在此Component中為單例的,則用Scope相關(guān)注解修飾Module的Provides和Binds方法。
(3). 如果依賴通過構(gòu)造方式注入,且該依賴在此Component中為單例的,則要用Scope修飾其類。
我們通過如下例子詳細說明,并進行測試和分析其原理:

以Singleton這個Scope是實現(xiàn)為例:
首先用它來修飾Component類:

@Singleton
@Component
public interface AppComponent {
    void inject(MainActivity mainActivity);
}

用通過構(gòu)造方法注入依賴圖的,用@Singleton修飾其類:

@Singleton
public class InfoRepository {
    private static final String TAG = "InfoRepository";

    @Inject
    InfoRepository() {
    }

    public void test() {
        Log.d(TAG, "test");
    }
}

實際注入到Activity類中如下:

public class MainActivity extends Activity {
    @Inject
    InfoRepository infoRepositoryA;
    @Inject
    InfoRepository infoRepositoryB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getComponent().inject(this);
        setContentView(R.layout.activity_main);
        Log.d("test", "a:"+infoRepositoryA.hashCode());
        Log.d("test", "b:"+infoRepositoryB.hashCode());
    }
}

如上代碼測試結(jié)果如下:

10-19 19:25:08.253 26699-26699/com.qt.daggerTest D/test: a:442589
10-19 19:25:08.254 26699-26699/com.qt.daggerTest D/test: b:442589

如上可見,兩次注入的InfoRepository對象為同一個。
如果將上面修飾InfoRepository的@Singleton注解去掉,結(jié)果是什么呢?經(jīng)過測試如下:

10-19 19:23:00.092 23014-23014/com.qt.daggerTest D/test: a:442589
10-19 19:23:00.092 23014-23014/com.qt.daggerTest D/test: b:160539730

也就是說在不加@Singleton注解時候,每次注入的時候都是new一個新的對象。
注意,如果我們將上面所有的@Singleton替換成我們自己的Scope注解其結(jié)果也是一致的,如替換成上文的ActivityScope。

下面,我們通過分析Dagger自動生成的代碼來分析如何實現(xiàn)單例的:

在注入類不加@Singleton注解時,生成的DaggerAppComponent類的initialize()方法如下:

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {
    this.mainActivityMembersInjector =
        MainActivity_MembersInjector.create(InfoRepository_Factory.create());
  }

而加@Singleton注解后的initialize()方法變成了:

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {

    this.infoRepositoryProvider = DoubleCheck.provider(InfoRepository_Factory.create());

    this.mainActivityMembersInjector =
        MainActivity_MembersInjector.create(infoRepositoryProvider);
  }

也是就是說提供InfoRepository的InfoRepositoryProvider替換成了DoubleCheck.provider(InfoRepository_Factory.create())。用DoubleCheck包裝了原來對象的Provider。DoubleCheck顧名思義,應(yīng)該是通過雙重檢查實現(xiàn)單例,我們看源碼確實如此:

public final class DoubleCheck<T> implements Provider<T>, Lazy<T> {
  private static final Object UNINITIALIZED = new Object();

  private volatile Provider<T> provider;
  private volatile Object instance = UNINITIALIZED;

  private DoubleCheck(Provider<T> provider) {
    assert provider != null;
    this.provider = provider;
  }

  @SuppressWarnings("unchecked") // cast only happens when result comes from the provider
  @Override
  public T get() {
    Object result = instance;
    if (result == UNINITIALIZED) {
      synchronized (this) {
        result = instance;
        if (result == UNINITIALIZED) {
          result = provider.get();
          /* Get the current instance and test to see if the call to provider.get() has resulted
           * in a recursive call.  If it returns the same instance, we'll allow it, but if the
           * instances differ, throw. */
          Object currentInstance = instance;
          if (currentInstance != UNINITIALIZED && currentInstance != result) {
            throw new IllegalStateException("Scoped provider was invoked recursively returning "
                + "different results: " + currentInstance + " & " + result + ". This is likely "
                + "due to a circular dependency.");
          }
          instance = result;
          /* Null out the reference to the provider. We are never going to need it again, so we
           * can make it eligible for GC. */
          provider = null;
        }
      }
    }
    return (T) result;
  ...
  }

其get方法就用了DoubleCheck方式保證了單例,其中還判斷如果存在循環(huán)依賴的情況下拋出異常。

注意,Scope只的單例是在Component的生命周期中相關(guān)依賴是單例的,也就是同一個Component對象注入的同類型的依賴是相同的。按上面例子,如果我們又創(chuàng)建了個AppComponent,它注入的InfoRepository對象與之前的肯定不是一個。

2. Component間依賴

在Android應(yīng)用中,如果我們需要不止一個Component,而Component的依賴圖中有需要其他Component依賴圖中的某些依賴時候,利用Component間依賴(Component Dependency)方式是個很好的選擇。在新建Component類時候可以在@Component注解里設(shè)置dependencies屬性,確定其依賴的Component。在被依賴的Component中,如果要暴露其依賴圖中的某個依賴給其他Component,要顯示的在其中定義方法,使該依賴對其他Component可見如:

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
    Application application();
}
@ActivityScope
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}

在ActivityComponent中,就可以使用AppComponent依賴圖中暴露出的Application依賴了。
非常清晰,Component依賴(Component Dependency)的方式適用于Component只將某個或某幾個依賴暴露給其他Component的情況下。

3.subComponent

定義subComponent是另一種方式使Component將依賴暴露給其他Component。當(dāng)我們需要一個Component,它需要繼承另外一個Component的所有依賴時,我們可以定義其為subComponent。
具體用法如下:首先在父Component的接口中定義方法,來獲得可以繼承它的subComponent:

@Singleton
@Component(
        modules = {AppModule.class}
)
public interface AppComponent {

    UserComponent plus(UserModule userModule);

}

其次,其subComponent被@SubComponent注解修飾,如下:

@UserScope
@Subcomponent(
        modules = {UserModule.class}
)
public interface UserComponent {
  ...
}

Dagger會實現(xiàn)上面在接口中定義的plus()方法,我們通過調(diào)用父Component的plus方法或者對應(yīng)的subComponent實例,具體如下:

userComponent = appComponent.plus(new UserModule(user));

這樣,我們就獲得了userComponent對象,可以利用他為其他類注入依賴了。
注意,subComponent繼承了其父Component的所有依賴圖,也就是說被subComponent可以向其他類注入其父Component的所有依賴。

4. 用多個Component組織你的Android應(yīng)用

前面幾部分中,我們介紹了如何創(chuàng)建多個Component/subComponent并使其獲得其他Component的依賴。這就為我們在應(yīng)用中用多個Component組織組織應(yīng)用提供了條件。文章http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ 提供了一個常用的思路:我們大概需要三個Component:AppComponent,UserComponent,ActivityComponent,如下:

摘自http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/

上文介紹了,各個Component要有自己的Scope且不能相同,所以這幾個Component對應(yīng)的Scope分別為@Singleton ,@UserScop,@ActivityScope。也就是說,依賴在對應(yīng)的Component生命周期(同個Component中)中都是單例的。而三個Component的生命周期都不同:AppComponent為應(yīng)用全局單例的,UserComponent的生命周期對應(yīng)了用戶登錄的生命周期(從用戶登錄一個賬戶到用戶退出登錄),ActivityComponent對應(yīng)了每個Activity的生命周期,如下:

Scopes lifecycle 摘自http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/

在具體代碼中,我們通過控制Component對象的生命周期來控制依賴圖的周期,以UserComponent為例,在用戶登錄時候創(chuàng)建UserComponent實例,期間一直用該實例為相關(guān)類注入依賴,當(dāng)其退出時候?qū)serComponent實例設(shè)為空,下次登錄時候重新創(chuàng)建個UserComponent,大致如下:

    public class MyApplication extends Application {
      ...
    private void initAppComponent() {
        appComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }

    public UserComponent createUserComponent(User user) {
        userComponent = appComponent.plus(new UserModule(user));
        return userComponent;
    }

    public void releaseUserComponent() {
        userComponent = null;
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    public UserComponent getUserComponent() {
        return userComponent;
    }

}

createUserComponent和releaseUserComponent在用戶登入和登出時候調(diào)用,所以在不同用戶中用的是不同UserComponent對象注入,注入的依賴也不同。而AppComponent對象只有一個,所以其依賴圖中的依賴為全局單例的。而對于ActivityComponent,則可以在Activity的onCreate()中生成ActivityComponent對象來為之注入依賴。

5.多Component情況下Scope的使用限制

Scope和多個Component在具體使用時候有一下幾點限制需要注意:
(1). Component和他所依賴的Component不能公用相同的Scope,每個Component都要有自己的Scope,編譯時會報錯,因為這有可能破壞Scope的范圍,可詳見https://github.com/google/dagger/issues/107#issuecomment-71073298。這種情況下編譯會報錯:

Error:(21, 1) 錯誤:com.qt.daggerTest.AppComponent depends on scoped components in a non-hierarchical scope ordering:
@com.qt.daggerTest.ActivityScope com.qt.daggerTest.AppComponent
@com.qt.daggerTest.ActivityScope com.qt.daggerTest.ActivityComponent

(2). @Singleton的Component不能依賴其他Component。這從意義和規(guī)范上也是說的通的,我們希望Singleton的Component應(yīng)為全局的Component。這種情況下編譯時會報錯:

Error:(23, 1) 錯誤: This @Singleton component cannot depend on scoped components:
@Singleton com.qt.daggerTest.AppComponent

(3). 無Scope的Component不能依賴有Scope的Component,因為這也會導(dǎo)致Scope被破壞。這時候編譯時會報錯:

Error:(20, 2) 錯誤: com.qt.daggerTest.ActivityComponent (unscoped) cannot depend on scoped components:
@com.qt.daggerTest.ActivityScope com.qt.daggerTest.AppComponent

(4). Module以及通過構(gòu)造函數(shù)注入依賴圖的類和其Component不可有不相同的Scope,這種情況下編譯時會報:

Error:(6, 1) 錯誤: com.qt.daggerTest.AppComponent scoped with @com.qt.daggerTest.ActivityScope may not reference bindings with different scopes:
@Singleton class com.qt.daggerTest.InfoRepository

總結(jié)

在上一篇Dagger2介紹與使用(http://www.lxweimin.com/p/f56d5b7e8b4d)的基礎(chǔ)之上,本文圍繞著Android中多個Component情況下如何使用的問題展開了分析。首先說明了如何通過Scope和Component管理依賴的生命周期,再介紹了通過Component間依賴和subComponent兩種方式完成一個Component將自己的依賴圖暴露給其他Component的過程。然后介紹如一般在Android應(yīng)用中如何劃分Component,維護不同生命周期的依賴。
經(jīng)過兩篇文章的介紹,Dagger2的使用基本清晰。Dagger2在處理Android應(yīng)用的依賴非常得心應(yīng)手,通過依賴注入的方式實現(xiàn)依賴反轉(zhuǎn),用容器(Component)來控制了所有依賴,使應(yīng)用各個組件的依賴更加清晰。Dagger2的各種功能也比較靈活,能夠應(yīng)付Android應(yīng)用依賴關(guān)系的各種復(fù)雜場景。

參考:
https://stackoverflow.com/questions/28411352/what-determines-the-lifecycle-of-a-component-object-graph-in-dagger-2
http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/
https://stackoverflow.com/questions/36447251/dagger-2-constructor-injection-scope
http://www.lxweimin.com/p/5ce4dcc41ec7
http://www.lxweimin.com/p/fbd62868a07b
https://my.oschina.net/rengwuxian/blog/287892

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容