依賴注入利器 - Dagger ?

概述

在開(kāi)發(fā)過(guò)程中,為了實(shí)現(xiàn)解耦,我們經(jīng)常使用依賴注入,常見(jiàn)的依賴注入方式有:

  • 構(gòu)造方法注入:在構(gòu)造方法中把依賴作為參數(shù)傳遞進(jìn)去
  • setter方法注入:添加setter方法,把依賴傳遞進(jìn)去
  • 接口注入:把注入方法抽到一個(gè)接口中,然后實(shí)現(xiàn)該接口,把依賴傳遞進(jìn)去

下面用一個(gè)小栗子來(lái)說(shuō)明三種方式的用法:

public class PersonService implements DependencyInjecter {

    private PersonDao personDao;

    // 構(gòu)造方法注入
    public PersonService(PersonDao personDao) {
        this.personDao = personDao;
    }

    // setter方法注入
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    // 接口注入:實(shí)現(xiàn)DependencyInjecter接口
    @Override
    public void injectPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    ... ... 
}

我們來(lái)看下使用一般的依賴注入方法時(shí),代碼會(huì)是怎么樣的:

public class MainActivity extends AppCompatActivity {

    private PersonService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 創(chuàng)建PersonService的依賴:personDao
        PersonDao personDao = new PersonDaoImpl();
        // 通過(guò)構(gòu)造方法注入依賴
        mService = new PersonService(personDao);
    }
}

看起來(lái)還好是吧?但現(xiàn)實(shí)情況下,依賴情況往往是比較復(fù)雜的,比如很可能我們的依賴關(guān)系如下圖:


2019-9-2-11-38-41.png

PersonDaoImpl依賴類A,類A依賴B,B依賴C和D...在這種情況下,我們就要寫(xiě)出下面這樣的代碼了:

public class MainActivity extends AppCompatActivity {

    private PersonService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 創(chuàng)建依賴D
        D d = new D();
        // 創(chuàng)建依賴C
        C c = new C();
        // 創(chuàng)建依賴B
        B b = new B(c, d);
        // 創(chuàng)建依賴A
        A a = new A(b);
        // 創(chuàng)建PersonService的依賴:personDao
        PersonDao personDao = new PersonDaoImpl(a);
        // 通過(guò)構(gòu)造方法注入依賴
        mService = new PersonService(personDao);
    }
}

MainActivity只是想使用PersonService而已,卻不得不關(guān)注PersonService的依賴是什么、PersonDaoImpl依賴的依賴是什么,需要把整個(gè)依賴關(guān)系搞清楚才能使用PersonService。而且還有一個(gè)不好的地方,一旦依賴關(guān)系變更了,比如A不再依賴B了,那么就得修改所有創(chuàng)建A的地方。那么,有沒(méi)有更好的方式呢?Dagger就是為此而生的,讓我們看看使用Dagger后,MainActivity會(huì)變成什么模樣:

public class MainActivity extends AppCompatActivity {

    @Inject
    PersonService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Dagger注入,讀者現(xiàn)在可先不關(guān)注里面做了什么操作
        DaggerPersonServiceComponent.create().inject(MainActivity.this);

        // 注意,mService已經(jīng)是非空了,可以正常使用
        mService.update(1, "HansChen");
        ......
    }
}

之前創(chuàng)建A、B、C、D、PersonDaoImpl等依賴的代碼全不見(jiàn)了,只需要調(diào)用一個(gè)注入語(yǔ)句就全搞定了。調(diào)用了注入語(yǔ)句之后,mService就可以正常使用了,是不是挺方便呢?至于這句注入語(yǔ)句具體干了什么,讀者現(xiàn)在可以先不管,后面會(huì)有詳細(xì)說(shuō)明,這里只是做一個(gè)使用演示而已。

我們大概猜想一下,在MainActivity使用PersonService需要做哪些?

  1. 分析生成依賴關(guān)系圖,如PersonService-->PersonDaoImpl-->A-->B-->C&D
  2. 根據(jù)依賴關(guān)系圖獲取相關(guān)依賴,比如依次創(chuàng)建D、C、B、A、PersonDaoImpl、PersonService的實(shí)例
  3. 把生成的PersonService實(shí)例傳遞給MainActivity的mService成員變量

其實(shí)Dagger做的也就是上面這些事情了,接下來(lái)就讓我們真正開(kāi)始學(xué)習(xí)Dagger吧

聲明需要注入的對(duì)象

首先我們應(yīng)該用javax.inject.Inject去注解需要被自動(dòng)注入的對(duì)象,@Inject是Java標(biāo)準(zhǔn)的依賴注入(JSR-330)注解。比如下面栗子中,需要注入的對(duì)象就是MainActivity的mService。這里有個(gè)要注意的地方,被@Inject注解的變量不能用private修飾

public class MainActivity extends AppCompatActivity {

    // 注意,不能被private修飾
    @Inject
    PersonService mService;
    ......
}

如何實(shí)例化出依賴?

在執(zhí)行依賴注入的時(shí)候,Dagger會(huì)查找@Inject注解的成員變量,并嘗試獲取該類的實(shí)例,Dagger最直接的方式就是直接new出相應(yīng)的對(duì)象了。實(shí)例化對(duì)象的時(shí)候,會(huì)調(diào)用對(duì)象的構(gòu)造方法,但假如有多個(gè)構(gòu)造方法,具體用哪個(gè)構(gòu)造方法來(lái)實(shí)例化對(duì)象?Dagger肯定是不會(huì)幫我們“擅自做主”的,用哪個(gè)構(gòu)造方法來(lái)實(shí)例化對(duì)象應(yīng)該是由我們做主的,所以我們需要給相應(yīng)的構(gòu)造方法添加@Inject注解
當(dāng)Dagger需要實(shí)例化該對(duì)象的時(shí)候,會(huì)調(diào)用@Inject注解的構(gòu)造方法來(lái)實(shí)例化對(duì)象:

public class PersonService implements DependencyInjecter {

    private PersonDao personDao;

    // 用@Inject注解,相當(dāng)于告訴Dagger需要實(shí)例化PersonService的時(shí)候,請(qǐng)調(diào)用這個(gè)構(gòu)造方法
    @Inject
    public PersonService(PersonDao personDao) {
        this.personDao = personDao;
    }

    ......
}

聰明的你應(yīng)該發(fā)現(xiàn)了,調(diào)用PersonService的構(gòu)造方法需要傳入PersonDao實(shí)例,所以要實(shí)例化PersonService,必須先要實(shí)例化PersonDao,Dagger會(huì)幫我們自動(dòng)分析出這個(gè)依賴關(guān)系,并把它添加到依賴關(guān)系圖里面!Dagger會(huì)嘗試先去實(shí)例化一個(gè)PersonDao,如果PersonDao又依賴于另外一個(gè)對(duì)象A,那么就先嘗試去實(shí)例化A......以此類推,是不是很像遞歸?當(dāng)所有依賴都被實(shí)例化出來(lái)之后,我們的PersonService當(dāng)然也被構(gòu)造出來(lái)了。

問(wèn)題又來(lái)了,如果PersonDao是一個(gè)接口呢?Dagger怎么知道這個(gè)接口應(yīng)該怎么實(shí)現(xiàn)?答案是不知道的,那么Dagger怎么實(shí)例化出一個(gè)接口出來(lái)?這個(gè)就是Module存在的意義之一了。關(guān)于Module的講解我們會(huì)在后面詳細(xì)說(shuō)明,我們現(xiàn)在只要知道,Module里面會(huì)定義一些方法,這些方法會(huì)返回我們的依賴,就像:

@Module
public class PersonServiceModule {

    /**
     * 提供PersonDao接口實(shí)例
     */
    @Provides
    PersonDao providePersonDao(A a) {
        return new PersonDaoImpl(a);
    }
}

Dagger根據(jù)需求獲取一個(gè)實(shí)例的時(shí)候,并不總是通過(guò)new出來(lái)的,它會(huì)優(yōu)先查找Module
中是否有返回相應(yīng)實(shí)例的方法,如果有,就調(diào)用Module的方法來(lái)獲取實(shí)例。

比如你用@Inject注解了一個(gè)成員變量,Dagger會(huì)查找Module中是否有用@Provides注解的,返回該類實(shí)例的方法,有的話就會(huì)調(diào)用provide方法來(lái)獲得實(shí)例,然后注入,如果沒(méi)有的話Dagger就會(huì)嘗試new出一個(gè)實(shí)例。就像我們現(xiàn)在這個(gè)栗子,PersonService依賴于PersonDao接口,Dagger不能直接為我們new出一個(gè)接口,但我們可以提供一個(gè)Module,在Module中定義一個(gè)返回PersonDao接口實(shí)例的方法,這樣,Dagger就可以解決實(shí)例化PersonDao的問(wèn)題了。

我們?cè)偈崂硪幌铝鞒?,如果我們用@Inject注解了一個(gè)成員變量,并調(diào)用注入代碼之后,Dagger會(huì)這樣處理:

  1. 查找Module中是否有用@Provides注解的,返回該類實(shí)例的方法
  2. 如果有,就調(diào)用那個(gè)provide方法來(lái)獲得實(shí)例,然后注入
  3. 如果沒(méi)有,就嘗試調(diào)用相應(yīng)的類中被@Inject注解的構(gòu)造方法new出一個(gè)實(shí)例,然后注入
  4. 如果沒(méi)有一個(gè)構(gòu)造方法被@Inject注解,Dagger會(huì)因不能滿足依賴而出錯(cuò)

所以假如一個(gè)變量被@Inject注解,要么在Module中提供provide方法獲取實(shí)例,要么該類提供一個(gè)被@Inject注解的構(gòu)造方法,否則Dagger會(huì)出錯(cuò)

Module的使用

一般而言,Dagger會(huì)獲取所有依賴的實(shí)例,比如當(dāng)需要一個(gè)TestBean的時(shí)候,會(huì)通過(guò)new TestBean()創(chuàng)建實(shí)例并注入到類中。但是,以下情況會(huì)就不好處理了:

  1. 需要生成的是一個(gè)接口,而Dagger不能直接實(shí)例化接口
  2. 不能在第三方庫(kù)的類中添加注解
  3. 可配置的對(duì)象必須是配置的

為了解決以上問(wèn)題,我們需要定義一個(gè)被@Module注解的類,在里面定義用@Provides注解的方法。用該方法返回所需的實(shí)例。

@Module
public class PersonServiceModule {

    @Provides
    D provideD() {
        return new D();
    }
    
    @Provides
    C provideC() {
        return new C();
    }

    @Provides
    B provideB(C c, D d) {
        return new B(c, d);
    }

    @Provides
    A provideA(B b) {
        return new A(b);
    }

    /**
     * 提供PersonDao實(shí)例
     */
    @Provides
    PersonDao providePersonDao(A a) {
        return new PersonDaoImpl(a);
    }
}

就像providePersonDao返回了PersonDao接口實(shí)例,Dagger雖然不能直接實(shí)例化出PersonDao接口,但卻可以調(diào)用Module的providePersonDao方法來(lái)獲得一個(gè)實(shí)例。providePersonDao方法需要傳入A的實(shí)例,那么這里也構(gòu)成了一個(gè)依賴關(guān)系圖。Dagger會(huì)先獲取A的實(shí)例,然后把實(shí)例傳遞給providePersonDao方法。

Component的使用

到目前為止,我們雖然知道了:

  • Dagger怎么獲取實(shí)例:
    • 從Module的provide方法中獲取
    • 通過(guò)@Inject注解的構(gòu)造方法new出新的實(shí)例
  • Dagger會(huì)推導(dǎo)provide方法和構(gòu)造方法的參數(shù),形成依賴圖,并“滿足”我們依賴圖的需求,獲取依賴的實(shí)例

看樣子需要注入的依賴可以獲取了,但是不是總覺(jué)得還有點(diǎn)“零碎”,整個(gè)流程還沒(méi)連貫起來(lái)?比如,Module既然是一個(gè)類,生成依賴圖的時(shí)候,怎么知道跟哪個(gè)Module掛鉤?即使最后生成了需要的實(shí)例,注入的“目的地”是哪里?怎么才能把它注入到“目的地”?殘缺的這部分功能,正是Component提供的,Component起到了一個(gè)橋梁的作用,貫通Module和注入目標(biāo)。我們來(lái)看看最開(kāi)始那個(gè)例子,我們是怎么進(jìn)行依賴注入的:

public class MainActivity extends AppCompatActivity {

    @Inject
    PersonService mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PersonServiceComponent component = DaggerPersonServiceComponent.builder()
                                                                       .personServiceModule(new PersonServiceModule())
                                                                       .build();
        // 注入,所有@Inject注解的成員變量都會(huì)同時(shí)注入
        component.inject(MainActivity.this);

        // 通過(guò)component獲取實(shí)例,注意,這里只是演示用法,其實(shí)mService在component.inject的時(shí)候已經(jīng)完成了注入
        mService = component.getPersonService();
    }
}

這個(gè)DaggerPersonServiceComponent是什么鬼?DaggerPersonServiceComponent其實(shí)是Dagger為我們自動(dòng)生成的類,它實(shí)現(xiàn)了一個(gè)Component接口(這個(gè)接口是需要我們自己寫(xiě)的),我們來(lái)看下它實(shí)現(xiàn)的接口長(zhǎng)什么樣子:

/**
 * 指定PersonServiceModule,當(dāng)需要獲取某實(shí)例的時(shí)候,會(huì)查找PersonServiceModule中是否有返回相應(yīng)類型的方法,有的話就通過(guò)該方法獲得實(shí)例
 *
 * @author HansChen
 */
@Component(modules = PersonServiceModule.class)
public interface PersonServiceComponent {

    /**
     * 查找activity中被@Inject注解的成員變量,并嘗試獲取相應(yīng)的實(shí)例,把實(shí)例賦給activity的成員變量
     * 注意函數(shù)格式:返回值為空、帶有一個(gè)參數(shù)
     */
    void inject(MainActivity activity);

    /**
     * Dagger會(huì)嘗試從Module中獲取PersonService實(shí)例,如果Module中不能獲取對(duì)應(yīng)實(shí)例,則通過(guò)PersonService的構(gòu)造方法new出一個(gè)實(shí)例
     * 注意函數(shù)格式:參數(shù)為空,返回值非空
     */
    PersonService getPersonService();
}

這個(gè)接口被Component注解修飾,它里面可以定義3種類型的方法:

  • 返回值為空,有一個(gè)參數(shù):查找參數(shù)中被@Inject注解的成員變量,并嘗試獲取相應(yīng)的實(shí)例(通過(guò)Module的provide方法或@Inject注解的構(gòu)造方法new出新的實(shí)例),把實(shí)例賦給參數(shù)的成員變量
  • 返回值非空,參數(shù)為空:獲取相應(yīng)實(shí)例并返回
  • 返回值是Component,參數(shù)是Moduld,通過(guò)該方法可以創(chuàng)建SubComponent實(shí)例

既然獲取實(shí)例的時(shí)候,有可能用到Module,那么就必須為這個(gè)Component指定使用的Module是什么。具體做法就是在@Component注解中指定modules。
定義好Component之后,Dagger會(huì)自動(dòng)幫我們生成實(shí)現(xiàn)類,這就是Dagger強(qiáng)大的地方!生成的類名格式是:Dagger+Component名。
Component提供了2種方法,一個(gè)是注入式方法,一個(gè)是獲取實(shí)例方法。具體用什么方法,就看個(gè)人需求了。一個(gè)Component其實(shí)也對(duì)應(yīng)了一個(gè)依賴圖,因?yàn)镃omponent使用哪個(gè)Module是確定不變的,依賴關(guān)系無(wú)非也就是跟Module和類的定義有關(guān)。一旦這些都確定下來(lái)了,在這個(gè)Component范圍內(nèi),依賴關(guān)系也就被確定下來(lái)了。額外再說(shuō)一點(diǎn),在Dagger1中,Component的功能是由ObjectGraph實(shí)現(xiàn)的,Component是用來(lái)代替它的。

Component定義好之后,build一下工程,Dagger就會(huì)自動(dòng)為我們生成實(shí)現(xiàn)類了,就可以使用自動(dòng)生成的實(shí)現(xiàn)類來(lái)進(jìn)行依賴注入了。到現(xiàn)在為止,我們已經(jīng)通過(guò)Dagger完成了依賴注入??赡芸雌饋?lái)比正常方法麻煩得多,但是Dagger框架可以讓依賴的注入和配置獨(dú)立于組件之外,它幫助你專注在那些重要的功能類上。通過(guò)聲明依賴關(guān)系和指定規(guī)則構(gòu)建整個(gè)應(yīng)用程序。

熟悉完Dagger基本的使用之后,接下來(lái)我們來(lái)講解一些稍微高級(jí)一點(diǎn)的用法:

Dagger的進(jìn)階使用

Components之間的關(guān)系

在Dagger中,Component之間可以有兩種關(guān)系:Subcomponents和Component dependencies。他們有什么作用呢?比如在我們應(yīng)用中,經(jīng)常會(huì)有一些依賴我們?cè)诟鱾€(gè)界面都使用得到,比如操作數(shù)據(jù)庫(kù)、比如網(wǎng)絡(luò)請(qǐng)求。假設(shè)我們有個(gè)ServerApi的接口,在頁(yè)面A、B、C都使用到了,那么我們要在頁(yè)面A、B、C的Component里面都能獲取到ServerApi的實(shí)例,但顯然,獲取ServerApi實(shí)例的方法都是一樣的,我們不想寫(xiě)重復(fù)的代碼。于是我們可定義一個(gè)ApplicationComponent,在里面返回ServerApi實(shí)例,通過(guò)Component之間的關(guān)系便可以共享ApplicationComponent提供的依賴圖。

下面通過(guò)Android中的一個(gè)小栗子來(lái)說(shuō)明Subcomponents和Component dependencies如何使用

dependencies

先說(shuō)明下各個(gè)模塊之間的關(guān)系
首先,我們定義一個(gè)ApplicationComponent,它定義了一個(gè)方法,通過(guò)它來(lái)獲得ServerApi實(shí)例。ApplicationComponent還關(guān)聯(lián)了ApplicationModule,這個(gè)Module是ServerApi實(shí)例的提供者,注意,這個(gè)Moduld還可以返回Context實(shí)例


2019-9-2-11-41-18.png
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    ServerApi getServerApi();
}
@Module
public class ApplicationModule {

    private final Context mAppContext;

    ApplicationModule(Context context) {
        mAppContext = context.getApplicationContext();
    }

    @Provides
    Context provideAppContext() {
        return mAppContext;
    }

    @Provides
    ServerApi provideServerApi(Context context) {
        return new ServerApiImpl(context);
    }
}
public class DemoApplication extends Application {

    private ApplicationComponent mAppComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build();
    }

    public ApplicationComponent getAppComponent() {
        return mAppComponent;
    }
}

MainActivity使用MVP模式,在MainPresenter里面需要傳入一個(gè)ServerApi對(duì)象


2019-9-2-11-43-13.png
// 注意,這里有個(gè)dependencies聲明
@Component(dependencies = ApplicationComponent.class, modules = MainPresenterModule.class)
public interface MainPresenterComponent {

    MainPresenter getMainPresenter();
}
@Module
public class MainPresenterModule {

    private MainView mMainView;

    public MainPresenterModule(MainView mainView) {
        this.mMainView = mainView;
    }

    @Provides
    MainView provideMainView() {
        return mMainView;
    }
}
public class MainPresenter {

    private MainView  mMainView;
    private ServerApi mServerApi;

    @Inject
    public MainPresenter(MainView mainView, ServerApi serverApi) {
        this.mMainView = mainView;
        this.mServerApi = serverApi;
    }
}

先拋開(kāi)dependencies,我們分析這個(gè)這個(gè)依賴樹(shù)是怎么樣的


2019-9-2-11-43-43.png

Component中g(shù)etMainPresenter的目的很簡(jiǎn)單,就是返回MainPresenter,而MainPresenter又依賴MainView和ServerApi,MainView還好說(shuō),在MainPresenterModule中有provide方法,但是ServerApi呢?就像上面說(shuō)的那樣,如果我們?cè)谶@個(gè)Moduld中也添加相應(yīng)的provide方法,那真是太麻煩了(當(dāng)然,這樣做完全是可以實(shí)現(xiàn)的),所以我們依賴了ApplicationComponent,通過(guò)dependencies,在被依賴的Component暴露的對(duì)象,在子Component中是可見(jiàn)的。這個(gè)是什么意思呢?意思有兩個(gè):

  1. 被依賴Component接口暴露的對(duì)象,可以添加到依賴者的依賴圖中
  2. Component接口沒(méi)有暴露的對(duì)象,依賴者是不可見(jiàn)的

對(duì)于第一點(diǎn)應(yīng)該比較好理解,就像這個(gè)栗子,MainPresenterComponent生成MainPresenter需要ServerApi,而ApplicationComponent中有接口暴露了ServerApi,所以MainPresenterComponent可以獲得ServerApi
對(duì)于第二點(diǎn),假設(shè)MainPresenter還需要傳入一個(gè)Context對(duì)象,我們注意到,ApplicationModule是可以提供Context的,那MainPresenterComponent能不能通過(guò)ApplicationComponent獲取Context實(shí)例?答案是不行的,因?yàn)锳pplicationComponent沒(méi)有暴露這個(gè)對(duì)象。想要獲取Context,除非ApplicationComponent中再添加一個(gè)getContext的方法。

他們之間的關(guān)系可以用下圖描述:


2019-9-2-11-44-12.png

Subcomponents

Subcomponents 實(shí)現(xiàn)方法一:

  • 先定義子 Component,使 用@Subcomponent 標(biāo)注(不可同時(shí)再使用 @Component)
  • 父 Component 中定義獲得子 Component 的方法

讓我們對(duì)上面的栗子改造改造:
去除MainPresenterComponent的Component注解,改為Subcomponent:

@Subcomponent(modules = MainPresenterModule.class)
public interface MainPresenterComponent {

    void inject(MainActivity activity);

    MainPresenter getMainPresenter();
}

在ApplicationComponent中新增plus方法(名字可隨意?。?,返回值為MainPresenterComponent,參數(shù)為MainPresenterModule:

@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    MainPresenterComponent plus(MainPresenterModule module);
}

這樣,就構(gòu)建了一個(gè)ApplicationComponent的子圖:MainPresenterComponent。子圖和dependencies的區(qū)別就是,子圖可以范圍父圖所有的依賴,也就是說(shuō),子圖需要的依賴,不再需要在父Component中暴露任何對(duì)象,可以直接通過(guò)父圖的Moduld提供!他們的關(guān)系變?yōu)榱耍?/p>

2019-9-2-11-44-34.png

這里需要注意的是,以上代碼直接在父 Component 返回子 Component 的形式,要求子 Component 依賴的 Module 必須包含一個(gè)無(wú)參構(gòu)造函數(shù),用以自動(dòng)實(shí)例化。如果 Module 需要傳遞參數(shù),則需要使用 @Subcomponent.builder 的方式,實(shí)現(xiàn)方法二實(shí)現(xiàn)步驟如下:

  • 在子 Component,定義一個(gè)接口或抽象類(通常定義為 Builder),使用 @Subcomponent.Builder 標(biāo)注
    • 編寫(xiě)返回值為 Builder,方法的參數(shù)為需要傳入?yún)?shù)的 Module
    • 編寫(xiě)返回值為當(dāng)前子 Component的 無(wú)參方法
  • 父 Component 中定義獲得子 Component.Builder 的方法

代碼如下:

@Module
public class TestModule {
    public TestModule(String test) {
    }

    @Provides
    AuthManager provideAuthManager() {
        return AuthManager.getInstance();
    }
}

@Subcomponent(modules = {TestModule.class})
public interface TestComponent {

    AuthManager getAuthManager();

    @Subcomponent.Builder
    interface Builder {

        Builder createBuilder(TestModule module);

        TestComponent build();
    }
}

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
    ...
    TestComponent.Builder testComponentBuilder();
}


// 使用
TestComponent testComponent = mApplicationComponent.testComponentBuilder().createBuilder(new TestModule("test")).build();

Binds注解

在Dagger2中,一般都是使用@provide方法注入接口。在Android 中,一般我們會(huì)這樣做,創(chuàng)建一個(gè)接口 Presenter 命名 為 HomePresenter

public interface HomePresenter {
   Observable<List<User>> loadUsers()
}

然后創(chuàng)建一個(gè)這個(gè)接口的實(shí)例:HomePresenterImp

public class HomePresenterImp implements HomePresenter {
    public HomePresenterImp(){
    }  
    @Override
    public Observable<List<User>> loadUsers(){
        //Return user list observable
    }
}

然后在 Module 中,提供實(shí)例化的 provide 方法:

@Module
public class HomeModule {
    @Provides
    public HomePresenter providesHomePresenter(){
        return new HomePresenterImp();
    }
}

但是,如果我們需要添加一個(gè)依賴到 presenter 叫 UserService,那就意味著,我們也要在 module 中添加一個(gè) provide 方法提供這個(gè) UserService,然后在 HomePresenterImp 類中加入一個(gè) UserService 參數(shù)的構(gòu)造方法。
有沒(méi)有覺(jué)得這種方法很麻煩呢?我們還可以用 @Binds 注解,如:

@Module
public abstract class HomeModule {
    // 變?yōu)?abstract 方法, 同時(shí) Module 也必須聲明為 abstract, 傳入的參數(shù)必須為返回參數(shù)的實(shí)現(xiàn)類
    // 當(dāng)需要 HomePresenter 時(shí),dagger 會(huì)自動(dòng)實(shí)例化 HomePresenterImp 并返回
    @Binds
    public abstract HomePresenter bindHomePresenter(HomePresenterImp homePresenterImp);
}

除了方便,使用 @Binds 注解還可以讓 dagger2 生成的代碼效率更高。但是需要注意的是,由于 Module 變?yōu)槌橄箢悾琈odule 不能再包含非 static 的帶 @Provides 注解的方法。而且這時(shí)候,依賴此 Module 的 Component 也不需要傳入此 Module 實(shí)例了(也實(shí)例化不了,因?yàn)樗浅橄蟮模?。相?dāng)于此 Module 僅僅作為描述依賴關(guān)系的一個(gè)類

Scopes

Scopes可是非常的有用,Dagger2可以通過(guò)自定義注解限定注解作用域。@Singleton是被Dagger預(yù)先定義的作用域注解。

  • 沒(méi)有指定作用域的@Provides方法將會(huì)在每次注入的時(shí)候都創(chuàng)建新的對(duì)象
  • 一個(gè)沒(méi)有scope的component不可以依賴一個(gè)有scope的組件component
  • 子組件和父組件的scope不能相同
  • Module中provide方法的scope需要與Component的scope一致

我們通常的ApplicationComponent都會(huì)使用Singleton注解,也就會(huì)是說(shuō)我們?nèi)绻远xcomponent必須有自己的scope。讀者到這里,可能還不能理解Scopes的作用,我們先來(lái)看下默認(rèn)提供的Singlton到底有什么作用,然后再討論Scopes的意義:

Singlton

Singletons是java提供的一個(gè)scope,我們來(lái)看看Singletons能做什么事情。
為@Provides注釋的方法或可注入的類添加添加注解@Singlton,構(gòu)建的這個(gè)對(duì)象圖表將使用唯一的對(duì)象實(shí)例,比如我們有個(gè)ServerApi
方法一:用@Singleton注解類:

@Singleton
public class ServerApi {

    @Inject
    public ServerApi() {
    }

    public boolean login(String username, String password) {
        return "HansChen".equals(username) && "123456".equals(password);
    }
}

方法二:用@Singleton注解Module的provide方法:

@Module
public class ApplicationModule {

    @Singleton
    @Provides
    ServerApi provideServerApi() {
        return new ServerApi();
    }
}

然后我們有個(gè)Component:

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {

    ServerApi getServerApi();
}

然后執(zhí)行依賴注入:

public class MainActivity extends AppCompatActivity {

    @Inject
    ServerApi mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ApplicationComponent component = DaggerApplicationComponent.create();
        Log.d("Hans", component.getServerApi().toString());
        Log.d("Hans", component.getServerApi().toString());
        Log.d("Hans", component.getServerApi().toString());
    }
}

使用了以上兩種方法的任意一種,我們都會(huì)發(fā)現(xiàn),通過(guò)component.getServerApi()獲得的實(shí)例都是同一個(gè)實(shí)例。不過(guò)要注意一點(diǎn)的是,如果類用@Singleton注解了,但Module中又存在一個(gè)provide方法是提供該類實(shí)例的,但provide方法沒(méi)有用@Singleton注解,那么Component中獲取該實(shí)例就不是單例的,因?yàn)闀?huì)優(yōu)先查找Module的方法。
這個(gè)單例是相對(duì)于同一個(gè)Component而言的,不同的Component獲取到的實(shí)例將會(huì)是不一樣的。

自定義Scope

既然一個(gè)沒(méi)有scope的component不可以依賴一個(gè)有scope的組件component,那么我們必然需要自定義scope來(lái)去注解自己的Component了,定義方法如下:

@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface FragmentScoped {
}

定義出來(lái)的FragmentScoped在使用上和Singleton是一樣的,那它和Singleton除了是不一樣的注解之外,還有什么不一樣呢?答案是沒(méi)有!我們自定義的scope和Singleton并沒(méi)有任何不一樣,不會(huì)因?yàn)镾ingleton是java自帶的注解就會(huì)有什么區(qū)別。

那么,這個(gè)scope的設(shè)定是為了什么呢?

scope的作用

scope除了修飾provide方法可以讓我們獲得在同一個(gè)Component實(shí)例范圍內(nèi)的單例之外,主要的作用就是對(duì)Component和Moduld的分層管理以及依賴邏輯的可讀性。
這里借用一個(gè)網(wǎng)絡(luò)上的圖片說(shuō)明:


2019-9-2-11-44-58.png

ApplicationComponent一般會(huì)用singleton注解,相對(duì)的,它的Module中provide方法也只能用singleton注解。UserComponent是用UserSCope能直接使用ApplicationModule嗎?不能!因?yàn)樗麄z的scope不一致,這就是這個(gè)設(shè)定帶來(lái)的好處,防止不同層級(jí)的組件混亂。另外,因?yàn)橛辛藄cope的存在,各種組件的作用和生命周期也變得可讀起來(lái)了

Lazy注入

有時(shí)可能會(huì)需要延遲獲取一個(gè)實(shí)例。對(duì)任何綁定的 T,可以構(gòu)建一個(gè) Lazy<T> 來(lái)延遲實(shí)例化直至第一次調(diào)用 Lazy<T> 的 get() 方法。注入之后,第一次get的時(shí)會(huì)實(shí)例化出 T,之后的調(diào)用都會(huì)獲取相同的實(shí)例。

public class MainActivity extends AppCompatActivity implements MainView {

    // 懶加載
    @Inject
    Lazy<MainPresenter> mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MainPresenterComponent component = DaggerMainPresenterComponent.builder()
                                                                       .mainPresenterModule(new MainPresenterModule(this))
                                                                       .applicationComponent(((DemoApplication) getApplication()).getAppComponent())
                                                                       .build();
        component.inject(this);
        Log.d("Hans", mPresenter.get().toString()); // 實(shí)例化MainPresenter
        Log.d("Hans", mPresenter.get().toString()); // 跟上次獲取的實(shí)例是同一個(gè)實(shí)例
    }
}

Provider注入

跟Lazy注入不一樣的是,有時(shí)候我們希望每次調(diào)用get的時(shí)候,獲取到的實(shí)例都是不一樣的,這時(shí)候可以用Provider注入

public class MainActivity extends AppCompatActivity implements MainView {

    // Provider
    @Inject
    Provider<MainPresenter> mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MainPresenterComponent component = DaggerMainPresenterComponent.builder()
                                                                       .mainPresenterModule(new MainPresenterModule(this))
                                                                       .applicationComponent(((DemoApplication) getApplication()).getAppComponent())
                                                                       .build();
        component.inject(this);
        Log.d("Hans", mPresenter.get().toString()); // 實(shí)例化MainPresenter
        Log.d("Hans", mPresenter.get().toString()); // 獲取新的MainPresenter實(shí)例
    }
}

Qualifiers注入

到目前為止,我們的demo里,Moduld的provide返回的對(duì)象都是不一樣的,但是下面這種情況就不好處理了:

@Module
public class ApplicationModule {

    ......
    
    // 返回ServerApi實(shí)例
    @Provides
    ServerApi provideServerApiA(Context context) {
        return new ServerApiImplA(context);
    }

    // 返回ServerApi實(shí)例
    @Provides
    ServerApi provideServerApiB(Context context) {
        return new ServerApiImplB(context);
    }
}

provideServerApiA和provideServerApiB返回的都是ServerApi,Dagger是無(wú)法判斷用哪個(gè)provide方法的。這時(shí)候就需要添加Qualifiers了:

@Module
public class ApplicationModule {

    ......

    @Provides
    @Named("ServerApiImplA")
    ServerApi provideServerApiA(Context context) {
        return new ServerApiImplA(context);
    }

    @Provides
    @Named("ServerApiImplB")
    ServerApi provideServerApiB(Context context) {
        return new ServerApiImplB(context);
    }
}

通過(guò)這樣一個(gè)限定,就能區(qū)分出2個(gè)方法的區(qū)別了,當(dāng)然,在使用過(guò)程中,也同樣要指明你用哪個(gè)name的實(shí)例,Dagger會(huì)根據(jù)你的name來(lái)選取對(duì)應(yīng)的provide方法:

public class MainPresenter {

    private MainView  mMainView;
    private ServerApi mServerApi;

    @Inject
    public MainPresenter(MainView mainView, @Named("ServerApiImplA") ServerApi serverApi) {
        this.mMainView = mainView;
        this.mServerApi = serverApi;
    }
}

除了用Named注解,你也可以創(chuàng)建你自己的限定注解:

@Qualifier
@Documented
@Retention(RUNTIME)
public @interface YourQualifier {
    String value() default "";
}

編譯時(shí)驗(yàn)證

Dagger 包含了一個(gè)注解處理器(annotation processor)來(lái)驗(yàn)證模塊和注入。這個(gè)過(guò)程很嚴(yán)格而且會(huì)拋出錯(cuò)誤,當(dāng)有非法綁定或綁定不成功時(shí)。下面這個(gè)例子缺少了 Executor:

@Module
class DripCoffeeModule {
    @Provides Heater provideHeater(Executor executor) {
        return new CpuHeater(executor);
    }
}

當(dāng)編譯時(shí),javac 會(huì)拒絕綁定缺少的部分:

[ERROR] COMPILATION ERROR :
[ERROR] error: java.util.concurrent.Executor cannot be provided without an @Provides-annotated method.

可以通過(guò)給方法 Executor 添加@Provides注解來(lái)解決這個(gè)問(wèn)題,或者標(biāo)記這個(gè)模塊是不完整的。不完整的模塊允許缺少依賴關(guān)系

@Module(complete = false)
class DripCoffeeModule {
    @Provides Heater provideHeater(Executor executor) {
        return new CpuHeater(executor);
    }
}

小結(jié)

第一次接觸用Dagger框架寫(xiě)的代碼時(shí)候,如果不了解各種注解作用的時(shí)候,那真會(huì)有一臉懵逼的感覺(jué),而且單看文章,其實(shí)還是很抽象,建議大家用Dagger寫(xiě)個(gè)小demo玩玩,很快就上手了,這里提供幾個(gè)使用Dagger的栗子,希望可以幫助大家上手Dagger

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容