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. 使用依赖注入的最大好处是什么?

sp161126_115417.png

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

Paste_Image.png

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

 
  1. public class A {

  2. ...

  3. B b;

  4. ...

  5. public A() {

  6. b = new B();

  7. }

  8. }

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

 
  1. @Inject

  2. 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。

图片1.png

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

3. 配置

Java Gradle

 
  1. // Add plugin https://plugins.gradle.org/plugin/net.ltgt.apt

  2. plugins {

  3. id "net.ltgt.apt" version "0.5"

  4. }

  5.  
  6. // Add Dagger dependencies

  7. dependencies {

  8. compile 'com.google.dagger:dagger:2.x'

  9. apt 'com.google.dagger:dagger-compiler:2.x'

  10. }

Android Gradle

 
  1. // Add Dagger dependencies

  2. dependencies {

  3. compile 'com.google.dagger:dagger:2.x'

  4. annotationProcessor 'com.google.dagger:dagger-compiler:2.x'

  5. }

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

4. 简单的例子

实现Module

继续上面的例子:

 
  1. @Module // 注明本类是Module

  2. public class MyModule{

  3. @Provides // 注明该方法是用来提供依赖对象的方法

  4. public B provideB(){

  5. return new B();

  6. }

  7. }

实现Component

 
  1. @Component(modules={ MyModule.class}) // 指明Component查找Module的位置

  2. public interface MyComponent{ // 必须定义为接口,Dagger2框架将自动生成Component的实现类,对应的类名是Dagger×××××,这里对应的实现类是DaggerMyComponent

  3. void inject(A a); // 注入到A(Container)的方法,方法名一般使用inject

  4. }

实现Container

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

 
  1. public A{

  2. @Inject //标记b将被注入

  3. B b; // 成员变量要求是包级可见,也就是说@Inject不可以标记为private类型。

  4. public void init(){

  5. DaggerMyComponent.create().inject(this); // 将实现类注入

  6. }

  7. }

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

5. 更多用法

方法参数

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

 
  1. @Module

  2. public class MyModule{

  3. @Provides

  4. public B provideB(C c){

  5. return new B(c);

  6. }

  7. @Provides

  8. pulic C provideC(){

  9. return new C();

  10. }

  11. }

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

 
  1. @Module

  2. public class MyModule{

  3. @Provides

  4. public B provideB(C c){

  5. return new B(c);

  6. }

  7. }

  8. public class C{

  9. @Inject

  10. Public C(){

  11. }

  12. }

添加多个Module

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

 
  1. @Component(modules={ModuleA.class,ModuleB.class,ModuleC.class})

  2. public interface MyComponent{

  3. ...

  4. }

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

 
  1. @Module(includes={ModuleA.class,ModuleB.class,ModuleC.class})

  2. public class MyModule{

  3. ...

  4. }

  5. @Component(modules={MyModule.class})

  6. public interface MyComponent{

  7. ...

  8. }

创建Module实例

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

 
  1. DaggerMyComponent.builder()

  2. .moduleA(new ModuleA())

  3. .moduleB(new ModuleB())

  4. .build()

区分@Provides 方法

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

 
  1. //定义Module

  2. @Module

  3. public class ActivityModule{

  4. private Context mContext ;

  5. private Context mAppContext = App.getAppContext();

  6. public ActivityModule(Context context) {

  7. mContext = context;

  8. }

  9. @Named("Activity")

  10. @Provides

  11. public Context provideContext(){

  12. return mContext;

  13. }

  14. @Named("Application")

  15. @Provides

  16. public Context provideApplicationContext (){

  17. return mAppContext;

  18. }

  19. }

  20.  
  21. //定义Component

  22. @Component(modules={ActivityModule.class})

  23. interface ActivityComponent{

  24. void inject(Container container);

  25. }

  26.  
  27. //定义Container

  28. class Container extends Fragment{

  29. @Named("Activity")

  30. @Inject

  31. Context mContext;

  32.  
  33. @Named("Application")

  34. @Inject

  35. Context mAppContext;

  36. ...

  37. public void init(){

  38. DaggerActivityComponent.

  39. .activityModule(new ActivityModule(getActivity()))

  40. .inject(this);

  41. }

  42.  
  43. }

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

 
  1. @Qualifier

  2. @Documented //起到文档提示作用

  3. @Retention(RetentionPolicy.RUNTIME) //注意注解范围是Runtime级别

  4. public @interface ContextLife {

  5. String value() default "Application"; // 默认值是"Application"

  6. }

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

 
  1. //定义Module

  2. @Module

  3. public class ActivityModule{

  4. private Context mContext ;

  5. private Context mAppContext = App.getAppContext();

  6. public ActivityModule(Context context) {

  7. mContext = context;

  8. }

  9. @ContextLife("Activity")

  10. @Provides

  11. public Context provideContext(){

  12. return mContext;

  13. }

  14. @ ContextLife ("Application")

  15. @Provides

  16. public Context provideApplicationContext (){

  17. return mAppContext;

  18. }

  19. }

  20.  
  21. //定义Component

  22. @Component(modules={ActivityModule.class})

  23. interface ActivityComponent{

  24. void inject(Container container);

  25. }

  26.  
  27. //定义Container

  28. class Container extends Fragment{

  29. @ContextLife ("Activity")

  30. @Inject

  31. Context mContext;

  32.  
  33. @ContextLife ("Application")

  34. @Inject

  35. Context mAppContext;

  36. ...

  37. public void init(){

  38. DaggerActivityComponent.

  39. .activityModule(new ActivityModule(getActivity()))

  40. .inject(this);

  41.  
  42. }

  43.  
  44. }

组件间依赖

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

 
  1. //定义ApplicationModule

  2. @Module

  3. public class ApplicationModule {

  4. private App mApplication;

  5.  
  6. public ApplicationModule(App application) {

  7. mApplication = application;

  8. }

  9.  
  10. @Provides

  11. @ContextLife("Application")

  12. public Context provideApplicationContext() {

  13. return mApplication.getApplicationContext();

  14. }

  15.  
  16. }

  17.  
  18. //定义ApplicationComponent

  19. @Component(modules={ApplicationModule.class})

  20. interface ApplicationComponent{

  21. @ContextLife("Application")

  22. Context getApplication(); // 对外提供ContextLife类型为"Application"的Context

  23. }

  24.  
  25. //定义ActivityComponent

  26. @Component(dependencies=ApplicationComponent.class, modules=ActivityModule.class)

  27. interface ActivityComponent{

  28. ...

  29. }

6. 进阶用法

单例的使用

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

 
  1. @Module

  2. class MyModule{

  3. @Singleton // 标明该方法只产生一个实例

  4. @Provides

  5. B provideB(){

  6. return new B();

  7. }

  8. }

  9. @Singleton // 标明该Component中有Module使用了@Singleton

  10. @Component(modules=MyModule.class)

  11. class MyComponent{

  12. void inject(Container container)

  13. }

  14.  

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

自定义Scope

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

 
  1. @Scope

  2. @Documented

  3. @Retention(RUNTIME)

  4. public @interface Singleton{}

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

 
  1. @Scope

  2. @Documented

  3. @Retention(RetentionPolicy.RUNTIME)

  4. public @interface PerApp {

  5. }

  6.  
  7. @Scope

  8. @Documented

  9. @Retention(RetentionPolicy.RUNTIME)

  10. public @interface PerActivity {

  11. }

  12.  
  13. @PerApp的使用例:

  14. @Module

  15. public class ApplicationModule {

  16. private App mApplication;

  17.  
  18. public ApplicationModule(App application) {

  19. mApplication = application;

  20. }

  21.  
  22. @Provides

  23. @PerApp

  24. @ContextLife("Application")

  25. public Context provideApplicationContext() {

  26. return mApplication.getApplicationContext();

  27. }

  28.  
  29. }

  30.  
  31. @PerApp

  32. @Component(modules = ApplicationModule.class)

  33. public interface ApplicationComponent {

  34. @ContextLife("Application")

  35. Context getApplication();

  36.  
  37. }

  38.  
  39. // 单例的有效范围是整个Application

  40. public class App extends Application {

  41. private static ApplicationComponent mApplicationComponent; // 注意是静态

  42. public void onCreate() {

  43. mApplicationComponent = DaggerApplicationComponent.builder()

  44. .applicationModule(new ApplicationModule(this))

  45. .build();

  46. }

  47.  
  48. // 对外提供ApplicationComponent

  49. public static ApplicationComponent getApplicationComponent() {

  50. return mApplicationComponent;

  51. }

  52. }

@PerActivity的使用例:

 
  1. // 单例的有效范围是Activity的生命周期

  2. public abstract class BaseActivity extends AppCompatActivity {

  3. protected ActivityComponent mActivityComponent; //非静态,除了针对整个App的Component可以静态,其他一般都不能是静态的。

  4. // 对外提供ActivityComponent

  5. public ActivityComponent getActivityComponent() {

  6. return mActivityComponent;

  7. }

  8.  
  9. public void onCreate() {

  10. mActivityComponent = DaggerActivityComponent.builder()

  11. .applicationComponent(App.getApplicationComponent())

  12. .activityModule(new ActivityModule(this))

  13. .build();

  14. }

  15. }

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

子组件

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

 
  1. //父Component:

  2. @Component(modules=××××)

  3. public AppComponent{

  4. SubComponent subComponent (); // 这里返回子Component

  5. }

  6. //子Component:

  7. @Subcomponent(modules=××××)

  8. public SubComponent{

  9. void inject(SomeActivity activity);

  10. }

  11.  
  12. // 使用子Component

  13. public class SomeActivity extends Activity{

  14. public void onCreate(Bundle savedInstanceState){

  15. App.getComponent().subCpmponent().inject(this); // 这里调用子Component

  16. }

  17. }

懒加载模式

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

 
  1. public class Container{

  2. @Inject Lazy<B> b;

  3. public void init(){

  4. DaggerComponent.create().inject(this);

  5. B b=b.get(); //调用get时才创建b

  6. }

  7. }

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

7. 结合MVP模式使用例

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

 
  1. // Module

  2. @Module

  3. public class ActivityModule {

  4. private Activity mActivity;

  5.  
  6. public ActivityModule(Activity activity) {

  7. mActivity = activity;

  8. }

  9.  
  10. @Provides

  11. @PerActivity

  12. @ContextLife("Activity")

  13. public Context ProvideActivityContext() {

  14. return mActivity;

  15. }

  16. }

  17.  
  18. // Component

  19. @PerActivity

  20. @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)

  21. public interface ActivityComponent {

  22.  
  23. @ContextLife("Activity")

  24. Context getActivityContext();

  25.  
  26. @ContextLife("Application")

  27. Context getApplicationContext();

  28.  
  29. void inject(NewsActivity newsActivity);

  30. }

  31.  
  32. // Presenter

  33. public class NewsPresenter {

  34. ...

  35. @Inject

  36. public NewPresenter () {

  37. }

  38. private void loadNews () {

  39. ...

  40. }

  41. ....

  42. }

  43.  
  44. // Activity

  45. public class NewsActivity extends BaseActivity

  46. implements NewsView {

  47. @Inject

  48. NewPresenter mNewsPresenter;

  49.  
  50. @Override

  51. protected void onCreate(Bundle savedInstanceState) {

  52. ...

  53. ActivityComponent activityComponent;

  54. activityComponent = DaggerActivityComponent.builder()

  55. .applicationComponent(App.getApplicationComponent())

  56. .activityModule(new ActivityModule(this))

  57. .build();

  58. activityComponent.inject(this);

  59.  
  60. mNewsPresenter.loadNews();

  61.  
  62. }

  63. }

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值