Dagger2实战

当前比较流行的Android开发框架当属MVP、RxJava、Retrofit2、Dagger2了,而在这些框架之中,学习成本最高也是最难上手的应该就是Dagger2了
但是作为程序员这种需要与时俱进的行业,毕竟不进步就是落后嘛,了解并掌握Dagger2还是是很有必要的。

Dagger2介绍

1. Dagger2是什么?

Dagger2在Github主页上的自我介绍是:“A fast dependency injector for Android and Java“(一个提供给Android和Java使用的快速依赖注射器。)
Dagger2是由谷歌接手开发,最早的版本Dagger1 是由Square公司开发的。

2. Dagger2相较于Dagger1的优势是什么?

更好的性能:相较于Dagger1,它使用的预编译期间生成代码来完成依赖注入,而不是用的反射。大家知道反射对手机应用开发影响是比较大的,因为反射是在程序运行时加载类来进行处理所以会比较耗时,而手机硬件资源有限,所以相对来说会对性能产生一定的影响。
容易跟踪调试:因为dagger2是使用生成代码来实现完整依赖注入,所以完全可以在相关代码处下断点进行运行调试。

3. 使用依赖注入的最大好处是什么?

[图片上传失败…(image-186007-1528449355056)]

没错,就是模块间解耦! 就拿当前Android非常流行的开发模式MVP来说,使用Dagger2可以将MVP中的V 层与P层进一步解耦,这样便可以提高代码的健壮性和可维护性。

[图片上传失败…(image-8adff1-1528449355056)]

如果在 Class A 中,有 Class B 的实例,则称 Class A 对 Class B 有一个依赖。
如果不用Dagger2的情况下我们应该这么写:

public class A {
    ...
    B b;
    ...
    public A() {
        b = new B();
    }
}

上面例子面临着一个问题,一旦某一天B的创建方式(如构造参数)发生改变,那么你不但需要修改A中创建B的代码,还要修改其他所有地方创建B的代码。
如果我们使用了Dagger2的话,就不需要管这些了,只需要在需要B的地方写下:

@Inject
B b;

Dagger2使用

上面我们对Dagger2有了个初步的了解,接下来我们来看看Dagger2的基本使用内容。

1. 注解

Dagger2 通过注解来生成代码,定义不同的角色,主要的注解如下:
@Module: Module类里面的方法专门提供依赖,所以我们定义一个类,用@Module注解,这样Dagger在构造类的实例的时候,就知道从哪里去找到需要的依赖。
**@Provides: **在Module中,我们定义的方法是用这个注解,以此来告诉Dagger我们想要构造对象并提供这些依赖。
**@Inject: **通常在需要依赖的地方使用这个注解。换句话说,你用它告诉Dagger这个类或者字段需要依赖注入。这样,Dagger就会构造一个这个类的实例并满足他们的依赖。
**@Component: **Component从根本上来说就是一个注入器,也可以说是@Inject和@Module的桥梁,它的主要作用就是连接这两个部分。将Module中产生的依赖对象自动注入到需要依赖实例的Container中。
@Scope: Dagger2可以通过自定义注解限定注解作用域,来管理每个对象实例的生命周期。
**@Qualifier: **当类的类型不足以鉴别一个依赖的时候,我们就可以使用这个注解标示。例如:在Android中,我们会需要不同类型的context,所以我们就可以定义 qualifier注解“@perApp”和“@perActivity”,这样当注入一个context的时候,我们就可以告诉 Dagger我们想要哪种类型的context。

2. 结构

Dagger2要实现一个完整的依赖注入,必不可少的元素有三种:Module,Component,Container。

[图片上传失败…(image-ab1fa6-1528449355056)]

为了便于理解,其实可以把component想象成针管,module是注射瓶,里面的依赖对象是注入的药水,build方法是插进患者(Container),inject方法的调用是推动活塞。

3. 配置

Java Gradle

// Add plugin https://plugins.gradle.org/plugin/net.ltgt.apt
plugins {
  id "net.ltgt.apt" version "0.5"
}

// Add Dagger dependencies
dependencies {
  compile 'com.google.dagger:dagger:2.x'
  apt 'com.google.dagger:dagger-compiler:2.x'
}

Android Gradle

// Add Dagger dependencies
dependencies {
  compile 'com.google.dagger:dagger:2.x'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
}

如果使用的Android gradle plugin 版本低于2.2请参考这里

4. 简单的例子

实现Module

继续上面的例子:

@Module // 注明本类是Module
public class MyModule{
    @Provides  // 注明该方法是用来提供依赖对象的方法
    public B provideB(){
        return new B();
    }
}

实现Component

@Component(modules={ MyModule.class}) // 指明Component查找Module的位置
public interface MyComponent{    // 必须定义为接口,Dagger2框架将自动生成Component的实现类,对应的类名是Dagger×××××,这里对应的实现类是DaggerMyComponent 
    void inject(A a);   // 注入到A(Container)的方法,方法名一般使用inject
 }

实现Container

A就是可以被注入依赖关系的容器。

public A{
     @Inject   //标记b将被注入
     B b;   // 成员变量要求是包级可见,也就是说@Inject不可以标记为private类型。 
     public void init(){
         DaggerMyComponent.create().inject(this); // 将实现类注入
     }
 }

当调用A的init()方法时, b将会自动被赋予实现类的对象。

5. 更多用法

方法参数

上面的例子@Provides标注的方法是没有输入参数的,Module中@Provides标注的方法是可以带输入参数的,其参数值可以由Module中的其他被@Provides标注的方法提供。

@Module
public class MyModule{
    @Provides
    public B provideB(C c){         
        return new B(c);
    }
    @Provides
    pulic C provideC(){
        return new C();
    }
}

如果找不到被@Provides注释的方法提供对应参数对象的话,将会自动调用被@Inject注释的构造方法生成相应对象。

@Module
public class MyModule{
    @Provides
    public B provideB(C c){
        return new B(c);
    }
}
public class C{
    @Inject
    Public C(){
    }
}

添加多个Module

一个Component可以添加多个Module,这样Component获取依赖时候会自动从多个Module中查找获取。添加多个Module有两种方法,一种是在Component的注解@Component(modules={××××,×××})中添加多个modules

@Component(modules={ModuleA.class,ModuleB.class,ModuleC.class}) 
public interface MyComponent{
    ...
}

另外一种添加多个Module的方法可以使用@Module的 includes的方法(includes={××××,×××})

@Module(includes={ModuleA.class,ModuleB.class,ModuleC.class})
public class MyModule{
    ...
}
@Component(modules={MyModule.class}) 
public interface MyComponent{
    ...
}

创建Module实例

上面简单例子中,当调用DaggerMyComponent.create()实际上等价于调用了DaggerMyComponent.builder().build()。可以看出,DaggerMyComponent使用了Builder构造者模式。在构建的过程中,默认使用Module无参构造器产生实例。如果需要传入特定的Module实例,可以使用

DaggerMyComponent.builder()
.moduleA(new ModuleA()) 
.moduleB(new ModuleB())
.build()

区分@Provides 方法

这里以Android Context来举例。当有Context需要注入时,Dagger2就会在Module中查找返回类型为Context的方法。但是,当Container需要依赖两种不同的Context时,你就需要写两个@Provides方法,而且这两个@Provides方法都是返回Context类型,靠判别返回值的做法就行不通了。这就可以使用@Named注解来区分

//定义Module
@Module
public class ActivityModule{
private Context mContext    ;
private Context mAppContext = App.getAppContext();
    public ActivityModule(Context context) {
        mContext = context;
    }
    @Named("Activity")
    @Provides
    public Context provideContext(){  
        return mContext;
    }
    @Named("Application")
    @Provides
    public Context provideApplicationContext (){
        return mAppContext;
    }
}

//定义Component
@Component(modules={ActivityModule.class}) 
interface ActivityComponent{   
    void inject(Container container);   
}

//定义Container
class Container extends Fragment{
    @Named("Activity") 
    @Inject
    Context mContext; 

    @Named("Application") 
    @Inject
    Context mAppContext; 
    ...
    public void init(){
         DaggerActivityComponent.
     .activityModule(new ActivityModule(getActivity()))
     .inject(this);
     }

}

这样,只有相同的@Named的@Inject成员变量与@Provides方法才可以被对应起来。
更常用的方法是使用注解@Qualifier来自定义注解。

@Qualifier   
@Documented   //起到文档提示作用
@Retention(RetentionPolicy.RUNTIME)  //注意注解范围是Runtime级别
public @interface ContextLife {
    String value() default "Application";  // 默认值是"Application"
}

接下来使用我们定义的@ContextLife来修改上面的例子

//定义Module
@Module
public class ActivityModule{
private Context mContext    ;
private Context mAppContext = App.getAppContext();
    public ActivityModule(Context context) {
        mContext = context;
    }
    @ContextLife("Activity")
    @Provides
    public Context provideContext(){  
        return mContext;
    }
    @ ContextLife ("Application")
    @Provides
    public Context provideApplicationContext (){
        return mAppContext;
    }
}

//定义Component
@Component(modules={ActivityModule.class}) 
interface ActivityComponent{   
    void inject(Container container);   
}

//定义Container
class Container extends Fragment{
    @ContextLife ("Activity") 
    @Inject
    Context mContext; 

    @ContextLife ("Application") 
    @Inject
    Context mAppContext; 
    ...
    public void init(){
         DaggerActivityComponent.
     .activityModule(new ActivityModule(getActivity()))
     .inject(this);

     }

}

组件间依赖

假设ActivityComponent依赖ApplicationComponent。当使用ActivityComponent注入Container时,如果找不到对应的依赖,就会到ApplicationComponent中查找。但是,ApplicationComponent必须显式把ActivityComponent找不到的依赖提供给ActivityComponent。

//定义ApplicationModule
@Module
public class ApplicationModule {
    private App mApplication;

    public ApplicationModule(App application) {
        mApplication = application;
    }

    @Provides
    @ContextLife("Application")
    public Context provideApplicationContext() {
        return mApplication.getApplicationContext();
    }

}

//定义ApplicationComponent
@Component(modules={ApplicationModule.class})
interface ApplicationComponent{
    @ContextLife("Application")
    Context getApplication();  // 对外提供ContextLife类型为"Application"的Context
}

//定义ActivityComponent
@Component(dependencies=ApplicationComponent.class, modules=ActivityModule.class)
 interface ActivityComponent{
    ...
}

6. 进阶用法

单例的使用

创建某些对象有时候是耗时、浪费资源的或者需要确保其唯一性,这时就需要使用@Singleton注解标注为单例了。

@Module
class MyModule{
    @Singleton   // 标明该方法只产生一个实例
    @Provides
    B provideB(){
        return new B();
    }
}
@Singleton  // 标明该Component中有Module使用了@Singleton
@Component(modules=MyModule.class)
class MyComponent{
    void inject(Container container)
}

※注意:Java中,单例通常保存在一个静态域中,这样的单例往往要等到虚拟机关闭时候,该单例所占用的资源才释放。但是,Dagger通过注解创建出来的单例并不保持在静态域上,而是保留在Component实例中。所以说不同的Component实例提供的对象是不同的。

自定义Scope

@Singleton就是一种Scope注解,也是Dagger2唯一自带的Scope注解,下面是@Singleton的源码

@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton{}

可以看到定义一个Scope注解,必须添加以下三部分:
@Scope :注明是Scope
@Documented :标记文档提示
@Retention(RUNTIME) :运行时级别
对于Android,我们通常会定义一个针对整个APP全生命周期的@PerApp的Scope注解和针对一个Activity生命周期的@PerActivity注解,如下

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

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

@PerApp的使用例:
@Module
public class ApplicationModule {
    private App mApplication;

    public ApplicationModule(App application) {
        mApplication = application;
    }

    @Provides
    @PerApp
    @ContextLife("Application")
    public Context provideApplicationContext() {
        return mApplication.getApplicationContext();
    }

}

@PerApp
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
    @ContextLife("Application")
    Context getApplication();

}

// 单例的有效范围是整个Application
public class App extends Application {
private static  ApplicationComponent mApplicationComponent; // 注意是静态
    public void onCreate() {
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    // 对外提供ApplicationComponent
    public static ApplicationComponent getApplicationComponent() {
        return mApplicationComponent;
    }
}

@PerActivity的使用例:

// 单例的有效范围是Activity的生命周期
public abstract class BaseActivity extends AppCompatActivity {
    protected ActivityComponent mActivityComponent; //非静态,除了针对整个App的Component可以静态,其他一般都不能是静态的。
    // 对外提供ActivityComponent
    public ActivityComponent getActivityComponent() {
        return mActivityComponent;
    }

    public void onCreate() {
        mActivityComponent = DaggerActivityComponent.builder()
                .applicationComponent(App.getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .build();
    }
}

通过上面的例子可以发现,使用自定义Scope可以很容易区分单例的有效范围。

子组件

可以使用@Subcomponent注解拓展原有component。Subcomponent其功能效果优点类似component的dependencies。但是使用@Subcomponent不需要在父component中显式添加子component需要用到的对象,只需要添加返回子Component的方法即可,子Component能自动在父Component中查找缺失的依赖。

//父Component:
@Component(modules=××××)
public AppComponent{    
    SubComponent subComponent ();  // 这里返回子Component
}
//子Component:
@Subcomponent(modules=××××)   
public SubComponent{
    void inject(SomeActivity activity); 
}

// 使用子Component
public class SomeActivity extends Activity{
    public void onCreate(Bundle savedInstanceState){
        App.getComponent().subCpmponent().inject(this); // 这里调用子Component
    }    
}

懒加载模式

可以使用Lazy来包装Container中需要被注入的类型为延迟加载。

public class Container{
    @Inject Lazy<B> b; 
    public void init(){
        DaggerComponent.create().inject(this);
        B b=b.get();  //调用get时才创建b
    }
}

另外可以使用Provider实现强制加载,每次调用get都会调用Module的Provides方法一次,和懒加载模式正好相反。

7. 结合MVP模式使用例

接下来看一下我们是如何在Activity中注入一个Presenter变量,来实现MVP的V层与P层之间的解耦。

// Module
@Module
public class ActivityModule {
    private Activity mActivity;

    public ActivityModule(Activity activity) {
        mActivity = activity;
    }

    @Provides
    @PerActivity
    @ContextLife("Activity")
    public Context ProvideActivityContext() {
        return mActivity;
    }
}

// Component
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {

    @ContextLife("Activity")
    Context getActivityContext(); 

    @ContextLife("Application")
    Context getApplicationContext();

    void inject(NewsActivity newsActivity);
}

// Presenter
public class NewsPresenter {
    ...
    @Inject
    public NewPresenter () {
    }
     private void loadNews () {
        ...
    }
    ....
}

// Activity
public class NewsActivity extends BaseActivity
        implements NewsView {
    @Inject
    NewPresenter mNewsPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    ActivityComponent activityComponent;
        activityComponent = DaggerActivityComponent.builder()
         .applicationComponent(App.getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .build();
        activityComponent.inject(this);

    mNewsPresenter.loadNews();

    }
}

在这个例子中,我们注入了一个名叫NewsPresenter的类,假设它负责在后台处理新闻数据。但是我们并没有在Module中提供生产NewsPresenter实例的Provides方法。这时根据Dagger2的注入规则,用@Inject注释的成员变量的依赖会首先从Module的@Provides方法集合中查找。如果查找不到的话,则会查找成员变量类型是否有@Inject构造方法,并会调用该构造方法注入该类型的成员变量。这时如果被@Inject注释的构造方法有参数的话,则将会继续使用注入规则进行递归查找。

完整的例子用法大家可以参考我在GitHub上的开源项目:ColorfulNews

最后

推荐大家有时间去看一下Dagger帮我们自动生成的代码,感觉就像是自己手敲的一样,非常便于理解,也很方便我们进行排错调试。Dagger2的生成源码里面也是用到了很多设计模式,如装饰模式、建造者模式等,非常值得我们学习借鉴。比如当我们调用inject(container)方法进行注入时,其实对应的生成代码里面用的就是装饰者模式,将container传进去进行包装赋值,这也就是为什么我们不能使用private修饰被@Inject注释的变量的原因,如果不这样做的话外界将不能访问Container中的变量进行赋值。

作者:咖枯
链接:https://www.jianshu.com/p/4db940c8da97
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    原文作者:高永峰
    原文地址: https://www.jianshu.com/p/c7caadaf28af
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞