2017-05-06 82 views
2

我正在學習Dagger 2,所以我想了解一些基本的東西。我有以下代碼:如何聲明依賴關係

@Module 
public class MainModule { 

@Provides 
public Presenter provideMainActivityPresenter(Model model){ 
    return new MainPresenter(model); 

} 

@Provides 
public Model provideMainModel(){ 
    return new MainModel(); 
} 
} 

和我MainPresenter類看起來是這樣的:

public class MainPresenter implements Presenter { 

@Nullable 
private ViewImpl view; 
private Model model; 



public MainPresenter(Model model) { 
    this.model = model; 
} 

@Override 
public void setView(ViewImpl view) { 
    this.view = view; 
    } 
} 

,而不是上面的代碼,可能我這樣做?

public class MainPresenter implements Presenter { 

@Nullable 
private ViewImpl view; 

@Inject 
Model model; 


@Override 
public void setView(ViewImpl view) { 
    this.view = view; 
} 
} 

因爲MainPresenter依賴於Model,它不是@Nullable
或者這是錯誤的?

我不明白時,我應該把依賴作爲一個構造函數參數,或者當我應該使用@Inject

+0

看起來你需要了解Dagger的基礎知識。試試這個教程:https://www.techyourchance.com/dagger-tutorial/ – Vasiliy

回答

4

你已經基本上3的方式來使用匕首

  • 構造方法注入
  • 場注射
  • 從模塊自己提供它

(也有創建對象後調用方法的方法注入)


以下是使用提供類的模塊。雖然沒有錯,但這是編寫和維護的最大開銷。您可以通過將所請求的依賴關係創建對象並返回它:

// in a module 

@Provides 
public Presenter provideMainActivityPresenter(Model model){ 
    // you request model and pass it to the constructor yourself 
    return new MainPresenter(model); 
} 

這應該與需要額外設置的東西,比如GsonOkHttp,或Retrofit這樣就可以在一個地方與創建對象使用所需的依賴關係。


下將用於注射,你沒有訪問或不想使用constructo對象。您註釋字段,在組件註冊的方法注入你的對象:

@Component class SomeComponent { 
    void injectPresenter(MainPresenter presenter); 
} 

public class MainPresenter implements Presenter { 

    // it's not annotated by @Inject, so it will be ignored 
    @Nullable 
    private ViewImpl view; 

    // will be field injected by calling Component.injectPresenter(presenter) 
    @Inject 
    Model model; 

    // other methods, etc 
} 

這也將爲您提供開銷所有的類都在一個主持人註冊,當你不能使用構造應使用,像活動,片段或服務。這就是爲什麼所有這些Dagger示例都有這些onCreate() { DaggerComponent.inject(this); }方法來注入Android框架的一部分。


最重要的是你可以使用構造函數注入。你用@Inject註釋構造函數,並讓Dagger找出如何創建它。

public class MainPresenter implements Presenter { 

    // not assigned by constructor 
    @Nullable 
    private ViewImpl view; 

    // assigned in the constructor which gets called by dagger and the dependency is passed in 
    private Model model; 

    // dagger will call the constructor and pass in the Model 
    @Inject 
    public MainPresenter(Model model) { 
    this.model = model; 
    } 
} 

這隻需要你註釋你的類的構造函數和匕首將知道如何處理它,因爲所有的依賴(構造函數的參數,在這個例子中模式)可以提供。


上述所有將創建一個對象和方法可以/應當在不同的情況下使用。

所有這些方法或者將依賴關係傳遞給構造函數,或者直接注入@Inject註釋字段。應該在構造函數中使用依賴關係,或者使用@Inject註釋,以便Dagger知道它們。

我還寫了一篇關於the basic usage of Dagger 2的博客文章,並提供了一些進一步的細節。

+0

所以:如果需要額外的設置像Retrofit,Gson我可以使用模塊中的提供並在我需要使用的類中使用Inject我可以在構造函數中使用Inject? – ste9206

+1

@ ste9206沒錯。如果你可以修改構造函數,你可以使用構造函數注入,如果需要安裝,使用一個模塊,並且如果你不能訪問構造函數(例如Activities),則使用該組件註冊一個'inject(MyActivity a)'。 –

+0

所以注入(...)也很好用於碎片和服務,當然? – ste9206