聽說Dagger2能夠通過依賴關係並且不用通過手寫的大量模板代碼中的對象引用將會由它給你創建並傳遞到兌現各種。這是我第一步的認識。
首先Dagger的引入:
- 在整個項目的build.gradle中加入:
dependencies {
// other classpath definitions here
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
- 在app/build.gradle中分別加入
// add after applying plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
//經常忘寫了這個,往往報錯原因就是因爲少了這個
dependencies {
// apt command comes from the android-apt plugin
apt 'com.google.dagger:dagger-compiler:2.2'
compile 'com.google.dagger:dagger:2.2'
provided 'javax.annotation:jsr250-api:1.0'
}
需要注意的是provided代表編譯時需要的依賴,Dagger的編譯器生成依賴關係的代碼,並在編譯時添加到IDE 的class path中,只參與編譯,並不會打包到最終的apk中。apt是由android-apt插件提供,它並不會添加這些類到class path中,這些類只用於註解解析,應當避免使用這些類。
Dagger2的註解
- @Inject: 通常在需要依賴的地方使用這個註解。換句話說,你用它告訴Dagger這個類或者字段需要依賴注入。這樣,Dagger就會構造一個這個類的實例並滿足他們的依賴。
- @Module: Modules類裏面的方法專門提供依賴,所以我們定義一個類,用@Module註解,這樣Dagger在構造類的實例的時候,就知道從哪裏去找到需要的 依賴。modules的一個重要特徵是它們設計爲分區並組合在一起(比如說,在我們的app中可以有多個組成在一起的modules)。
- @Provides: 在modules中,我們定義的方法是用這個註解,以此來告訴Dagger我們想要構造對象並提供這些依賴。
- @Component: Components從根本上來說就是一個注入器,也可以說是@Inject和@Module的橋樑,它的主要作用就是連接這兩個部分。 Components可以提供所有定義了的類型的實例,比如:我們必須用@Component註解一個接口然後列出所有的 @Modules組成該組件,如 果缺失了任何一塊都會在編譯的時候報錯。所有的組件都可以通過它的modules知道依賴的範圍。
- @Scope: Scopes可是非常的有用,Dagger2可以通過自定義註解限定註解作用域。後面會演示一個例子,這是一個非常強大的特點,因爲就如前面說的一樣,沒必要讓每個對象都去了解如何管理他們的實例。
Dagger2的流程
我是看這個項目才大致瞭解了Dageer2的使用,非常不錯,今天的講解也從這個項目展開。frogermcs/GithubClient
上一步我們已經實現了Dagger2的導入生成。然後開始具體的使用了。
- 首先進行DaggerAppComponent
的初始化
public class GithubClientApplication extends Application {
private AppComponent appComponent;
private UserComponent userComponent;
public static GithubClientApplication get(Context context) {
return (GithubClientApplication) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
AndroidDevMetrics.initWith(this);
}
initAppComponent();
}
private void initAppComponent() {
//DaggerAppComponent是Dagger生成的代碼
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
//後面則是在appComponent添加新的module注入
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;
}
}
參考:
1. Google官方MVP+Dagger2架構詳解【從零開始搭建android框架系列(6)】
2. 從Dagger2基礎到Google官方架構MVP+Dagger2架構詳解
3. Dagger2 使用初步
4. frogermcs/GithubClient
5. 解鎖Dagger2使用姿勢(一)