听说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使用姿势(一)