Android开源框架--Dagger2详解

2023-11-29 00:04

本文主要是介绍Android开源框架--Dagger2详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

功名只向马上取,真是英雄一丈夫

一,定义

我们知道在一个类中,通常会定义其他类型的变量,这个变量就是我们所说的“依赖“。

对一个类的变量进行初始化,有两种方式。第一种,这个类自己进行初始化;第二种,其他外部的类帮你进行初始化。

其中第二种方式,由外部类进行初始化的方式就是我们所说的”依赖注入“。由于他是由外部来控制,因此又叫做”控制反转“。依赖注入和非依赖注入的区别就是,变量初始化工作是由谁来做的。前面我们提到过的创建型设计模式,工厂模式、builder模式,带参数的构造函数等,都是依赖注入。

因此,实际上我们一直都在使用“依赖注入“,对它其实并不陌生。而Dagger2的定位就是提供了用注解的方式来配置依赖的方法。因此Dagger2并不是提供依赖注入的能力,而是为依赖注入提供一种更简单的方法。
谷歌新推出的hilt相比于dagger2来说,使用起来要方便易懂的多,那么我们为什么还要去学习dagger2呢?因为dagger2与hilt的关系,就相当于okhttp3与retrofit2的关系。hilt只是对于dagger2的二次封装。而且现在许多大型的互联网项目使用的依然是dagger2,所以我们非常有必要去了解dagger2。

二,角色介绍

1,object:需要被创建的对象

2,module: 主要用来提供对象

3,component:用于组织module并进行注入

三,基本使用

1,在app的build.gradle下面添加依赖:

implementation 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

如果报错:Unable to load class 'javax.annotation.Generated'.

再添加依赖:

implementation'javax.annotation:javax.annotation-api:1.3.2'annotationProcessor("javax.annotation:javax.annotation-api:1.3.2")

2,创建一个用于注入的对象:

public class YuanZhen {
}

3,创建一个module,用来提供YuanZhen

@Module
public class YuanZhenModule {@Providespublic YuanZhen providerYuanZhen(){//后面所有需要YuanZhen对象的地方,都在这里提供return new YuanZhen();}
}

4,创建component,用于组织module并进行注入

@Component(modules = {YuanZhenModule.class})
public interface MyComponent {void injectMainActivity(MainActivity mainActivity);
}

5,注入到activity

public class MainActivity extends AppCompatActivity {@InjectYuanZhen yuanZhen;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}
}

6,编译项目,让APT生成需要的文件

关于APT不了解的,可以参考文章android注解之APT和javapoet_android javapoet-CSDN博客

7,使用:

public class MainActivity extends AppCompatActivity {@InjectYuanZhen yuanZhen;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//  DaggerMyComponent.create().injectMainActivity(this);DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).build().injectMainActivity(this);System.out.println("yz----"+yuanZhen.hashCode());}}

最后输出:

上面就是APT的基本使用,两种方式都可以

四,源码分析

对于源码的分析,主要是分析APT生成的三个文件

从 DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).build().injectMainActivity(this);

我们可以看出,一定是采用了Buidler建造者模式,不清楚的可以参考文章Android设计模式--Builder建造者模式-CSDN博客

首先分析DaggerMyComponent.builder()

public static Builder builder() {return new Builder();
}

可以看到是new了一个Buidler,我们再来看下Builder

public static final class Builder {private YuanZhenModule yuanZhenModule;private Builder() {}public MyComponent build() {if (yuanZhenModule == null) {this.yuanZhenModule = new YuanZhenModule();}return new DaggerMyComponent(this);}public Builder yuanZhenModule(YuanZhenModule yuanZhenModule) {this.yuanZhenModule = Preconditions.checkNotNull(yuanZhenModule);return this;}

 可以看到DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule())是将我们新创建的YuanZhenModule传入到了Builder里面。

然后 DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).build()则是创建了一个DaggerMyComponent对象。

private DaggerMyComponent(Builder builder) {assert builder != null;initialize(builder);
}

在DaggerMyComponent的构造函数中,调用了initialize方法。

private void initialize(final Builder builder) {this.providerYuanZhenProvider =YuanZhenModule_ProviderYuanZhenFactory.create(builder.yuanZhenModule);this.mainActivityMembersInjector =MainActivity_MembersInjector.create(providerYuanZhenProvider);
}

在initialize方法中,调用了YuanZhenModule_ProviderYuanZhenFactory的create方法,这是一个工厂模式,不清楚的请参考Android设计模式--工厂模式-CSDN博客

再来看看YuanZhenModule_ProviderYuanZhenFactory的create方法

public static Factory<YuanZhen> create(YuanZhenModule module) {return new YuanZhenModule_ProviderYuanZhenFactory(module);
}

创建了一个YuanZhenModule_ProviderYuanZhenFactory对象,接下来继续看YuanZhenModule_ProviderYuanZhenFactory的构造方法:

public YuanZhenModule_ProviderYuanZhenFactory(YuanZhenModule module) {assert module != null;this.module = module;
}

也就是将yuanZhenModule这个对象传递给了YuanZhenModule_ProviderYuanZhenFactory

然后我们继续回到initialize方法,看看 this.mainActivityMembersInjector =
      MainActivity_MembersInjector.create(providerYuanZhenProvider)的实现

public static MembersInjector<MainActivity> create(Provider<YuanZhen> yuanZhenProvider) {return new MainActivity_MembersInjector(yuanZhenProvider);
}

创建了一个MainActivity_MembersInjector对象,看看其构造方法:

public MainActivity_MembersInjector(Provider<YuanZhen> yuanZhenProvider) {assert yuanZhenProvider != null;this.yuanZhenProvider = yuanZhenProvider;
}

将刚才创建的YuanZhenModule_ProviderYuanZhenFactory对象传递给了MainActivity_MembersInjector;

最后 我们来看下

DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).build().injectMainActivity(this);

@Override
public void injectMainActivity(MainActivity mainActivity) {mainActivityMembersInjector.injectMembers(mainActivity);
}

调用了MainActivity_MembersInjector的injectMembers方法

@Override
public void injectMembers(MainActivity instance) {if (instance == null) {throw new NullPointerException("Cannot inject members into a null reference");}instance.yuanZhen = yuanZhenProvider.get();
}

然后又调用了YuanZhenModule_ProviderYuanZhenFactory的get方法

@Override
public YuanZhen get() {return Preconditions.checkNotNull(module.providerYuanZhen(), "Cannot return null from a non-@Nullable @Provides method");
}

在get方法中,最终调用了我们自己写的module的providerYuanZhen方法:

@Module
public class YuanZhenModule {@Providespublic YuanZhen providerYuanZhen(){//后面所有需要YuanZhen对象的地方,都在这里提供return new YuanZhen();}
}

这样就通过APT生成的代码,自动帮我们创建了对象。

五,单例使用

1,创建一个注解:

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

2,在component和Module中使用注解

@AppScope
@Component(modules = {YuanZhenModule.class})
public interface MyComponent {void injectMainActivity(MainActivity mainActivity);
}
@AppScope
@Module
public class YuanZhenModule {@AppScope@Providespublic YuanZhen providerYuanZhen(){//后面所有需要YuanZhen对象的地方,都在这里提供return new YuanZhen();}
}

3,在application中创建component 保证component是唯一的

public class MyApplication extends Application {private MyComponent myComponent;@Overridepublic void onCreate() {super.onCreate();myComponent= DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).build();}public MyComponent getMyComonent(){return myComponent;}
}

4,验证:

public class MainActivity extends AppCompatActivity {@InjectYuanZhen yuanZhen;@InjectYuanZhen yuanZhen2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);((MyApplication)getApplication()).getMyComonent().injectMainActivity(this);System.out.println("yz------"+yuanZhen.hashCode());System.out.println("yz------"+yuanZhen2.hashCode());}}

输出:

六,多个component组合依赖 

如果我们一个类有好几个对象需要依赖的话,dagger2是不能使用多个Component同时注入同一个类中的,这种情况需要进行Component的组合

新建一个object对象:

public class YuanZhen2 {
}

创建新的注解:

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

创建module:

@AppScope2
@Module
public class YuanZhen2Module {@AppScope2@Providespublic CuiJing provideYuanZhen2(){return new YuanZhen2();}
}

创建component:

@AppScope2
@Component(modules = {YuanZhen2Module.class})
public interface YuanZhen2Component {YuanZhen2 providerYuanZhen2();
}

进行依赖:

@AppScope
@Component(modules = {YuanZhenModule.class},dependencies = {YuanZhen2Component.class})
public interface MyComponent {void injectMainActivity(MainActivity mainActivity);
}

使用:

public class MainActivity extends AppCompatActivity {@InjectYuanZhen yuanZhen;@InjectYuanZhen2 yuanZhen2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//    DaggerMyComponent.create().injectMainActivity(this);DaggerMyComponent.builder().yuanZhenModule(new YuanZhenModule()).yuanZhen2Component(DaggerYuanZhen2Component.create()).build().injectMainActivity(this);System.out.println("yz----"+yuanZhen.hashCode());System.out.println("yz----"+yuanZhen2.hashCode());}}

输出:

注意:

1.多个component上面的scope不能相同

2.没有scope的组件不能去依赖有scope的组件

七,总结

dagger2源码使用到的主要是APT框架,工厂模式和builder模式,dagger2的使用较为复杂,但是现在很多主流app都在使用,所以掌握还是很有必要的。

这篇关于Android开源框架--Dagger2详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/430705

相关文章

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

前端CSS Grid 布局示例详解

《前端CSSGrid布局示例详解》CSSGrid是一种二维布局系统,可以同时控制行和列,相比Flex(一维布局),更适合用在整体页面布局或复杂模块结构中,:本文主要介绍前端CSSGri... 目录css Grid 布局详解(通俗易懂版)一、概述二、基础概念三、创建 Grid 容器四、定义网格行和列五、设置行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

《Node.js数据库CRUD项目示例详解(完美解决方案)》:本文主要介绍Node.js数据库CRUD项目示例详解(完美解决方案),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考... 目录项目结构1. 初始化项目2. 配置数据库连接 (config/db.js)3. 创建模型 (models/

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表