Android开源框架--Dagger2详解

news2024/9/23 23:26:46

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

一,定义

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

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

其中第二种方式,由外部类进行初始化的方式就是我们所说的”依赖注入“。由于他是由外部来控制,因此又叫做”控制反转“。依赖注入和非依赖注入的区别就是,变量初始化工作是由谁来做的。前面我们提到过的创建型设计模式,工厂模式、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 {

    @Provides
    public 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 {

    @Inject
    YuanZhen yuanZhen;

    @Override
    protected 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 {

    @Inject
    YuanZhen yuanZhen;

    @Override
    protected 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 {

    @Provides
    public 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
    @Provides
    public YuanZhen providerYuanZhen(){
        //后面所有需要YuanZhen对象的地方,都在这里提供
        return new YuanZhen();
    }
}

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

public class MyApplication extends Application {

    private MyComponent myComponent;
    @Override
    public void onCreate() {
        super.onCreate();
        myComponent= DaggerMyComponent.builder()
                .yuanZhenModule(new YuanZhenModule())
                .build();

    }
    public MyComponent getMyComonent(){
        return myComponent;
    }
}

4,验证:

public class MainActivity extends AppCompatActivity {

    @Inject
    YuanZhen yuanZhen;

    @Inject
    YuanZhen yuanZhen2;

    @Override
    protected 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
    @Provides
    public 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 {

    @Inject
    YuanZhen yuanZhen;

    @Inject
    YuanZhen2 yuanZhen2;

    @Override
    protected 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都在使用,所以掌握还是很有必要的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1263861.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux环境安装Java,Tomcat,Mysql,

1、Java的安装 载 jdk1.8 注&#xff1a;此处 CentOS7 是64位&#xff0c;所以下载的是&#xff1a;Linux x64&#xff0c; 文件类型为 tar.gz 的文件 JDK 官网地址&#xff1a;https://www.oracle.com/java/ cd /usr/local/ mkdir jdk cd jdk/tar -xvf jdk-8u202-linux-x64.…

pandas教程:US Baby Names 1880–2010 1880年至2010年美国婴儿姓名

文章目录 14.3 US Baby Names 1880–2010&#xff08;1880年至2010年美国婴儿姓名&#xff09;1 Analyzing Naming Trends&#xff08;分析命名趋势&#xff09;评价命名多样性的增长“最后一个字母”的变革变成女孩名字的男孩名字&#xff08;以及相反的情况&#xff09; 14.3…

【Docker项目实战】使用Docker部署Plik临时文件上传系统

【Docker实战项目】使用Docker部署Plik 临时文件上传系统 一、Plik介绍1.1 Plik简介1.2 Plik特点 二、本地环境介绍2.1 本地环境规划2.2 本次实践介绍 三、本地环境检查3.1 检查Docker服务状态3.2 检查Docker版本3.3 检查docker compose 版本 四、下载Plik镜像五、部署Plik临时…

学习知识随笔(Django)

文章目录 MVC与MTV模型MVCMTV Django目录结构Django请求生命周期流程图路由控制路由是什么路由匹配反向解析路由分发 视图层视图函数语法reqeust对象属性reqeust对象方法 MVC与MTV模型 MVC Web服务器开发领域里著名的MVC模式&#xff0c;所谓MVC就是把Web应用分为模型(M&#…

案例-某乎参数x-zse-96逆向补环境

文章目录 前言一、流程分析二、导出代码三、补环境总结 前言 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;不提供完整代码&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则…

Java代码的编译与执行过程

一、编译过程 1、javac 编译 Java源代码通过编译器&#xff08;javac&#xff09;编译为字节码文件(.class)。 idea中的 build 和 maven package等指令都可以编译为 .class 2、类加载器(Class Loader) 类加载器负责将类的字节码文件加载到内存中&#xff0c;以便在运行时创…

【RTP】5:从network收到rtp包到组帧之间的数据传递

m79 代码。从网络中收到rtp、rtcp 后交给call 进行处理这是因为call 具有PacketReceiver 的能力。收到的包是一个 :CopyOnWriteBuffer 类型:rtc::CopyOnWriteBuffer packetclass Call PacketReceiver 准备delivery包:返回delivery结果:}成功、包错误、ssrc未知 D:\zhb-dev\…

96.STL-遍历算法 transform

目录 transform 语法&#xff1a; 功能描述&#xff1a; 函数原型&#xff1a; 代码示例&#xff1a; transform 是 C 标准模板库&#xff08;STL&#xff09;中的一个算法&#xff0c;用于对一个范围内的元素进行转换并将结果存储到另一个范围。以下是简要解释和一个示例…

Ansys Lumerical|带 1D-2D 光栅的出瞳扩展器

附件下载 联系工作人员获取附件 此示例显示了设置和模拟出瞳扩展器 &#xff08;EPE&#xff09; 的工作流程&#xff0c;EPE 是波导型增强现实 &#xff08;AR&#xff09; 设备的重要组成部分。该工作流程将利用 Lumerical 和 Zemax OpticStudio 之间的动态链接功能 。为了…

「计算机网络」Cisco Packet Tracker计算机网络仿真器的使用

介绍 Cisco Packet Tracker&#xff1a;网络仿真工具&#xff0c;用于模拟网络配置。 &#xff08;一&#xff09;通过 带外管理 配置交换机&#xff08;Switch&#xff09; 带外&#xff1a;Out-of-Band, OOB写在前面&#xff1a;如何打开Console页面 1、模式转换 用户执行模…

绝对是全网最简单的git入门了!!!

git使用步骤&#xff08;重点&#xff01;&#xff01;&#xff01;&#xff09;&#xff1a; 下载git安装包&#xff1a; https://gitee.com/lihutao/go/blob/master/Git-2.40.0-64-bit.zip 或去官网下载&#xff1a;Git - Downloads 安装完成后在电脑桌面&#xff08;也可…

合并区间[中等]

一、题目 以数组intervals表示若干个区间的集合&#xff0c;其中单个区间为intervals[i] [starti, endi]。请你合并所有重叠的区间&#xff0c;并返回一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中的所有区间。 示例 1&#xff1a; 输入&#xff1a;intervals […

Vscode中字符串报错:Unknown word.cSpell

一. 报错现象 二. 原因 是vscode IDE工具中的插件 Code Spell Checker 会检查字符串的合理性&#xff0c;我们写的中式拼音的字符串&#xff0c;不是一个标准英文单词&#xff0c;就会提示错误&#xff0c;解决方法就是让该插件遇到特定词汇不报错 三. 解决方法

深入Android S (12.0) 探索Framework之输入系统IMS的构成与启动

文章目录 前言一、输入系统的基本组成部分二、输入系统相关源码分析1、IMS 构建1.1、SystemServer # startOtherServices()1.2、InputManagerService1.3、NativeInputManager # nativeInit()1.4、NativeInputManager1.5、InputManager1.6、InputDispatcher1.7、InputReader1.8、…

Vue路由嵌套和携带参数的几种方法

1、路由嵌套 路由嵌套逻辑&#xff1a; router.index.js中使用children嵌套子路由 //该文件专门用于创建整个文件的路由器 import VueRouter from vue-routerimport About from "/pages/About"; import Home from "/pages/Home"; import News from "…

蓝桥杯物联网竞赛_STM32L071_5_串口接收发送数据

理论&#xff1a; 串口采取异步通信&#xff0c;即不依赖时钟节拍来接收或发送数据&#xff0c;而是采用互相约定的波特率传输数据。 波特率与单位时间传输的比特数有关&#xff0c;波特率越大传输的数据越多 传输一个比特花费的时间T 1 / 比特率 接受和发送数据的时候需要…

vue中的插槽用法(动态插槽)

vue中提供了一种通讯方式叫插槽>分为&#xff1a;默认插槽、具名插槽(作用域插槽) 1. 当一个组件有不确定的结构时, 就需要使用slot技术了 2. 注意: 插槽内容是在父组件中编译后, 再传递给子组件 3. 如果决定结构的数据在父组件, 那用默认slot或具名slot (1) 当只有一个不…

WPF创建进度条

使用wpf做一个原生的进度条&#xff0c;进度条上面有值&#xff0c;先看效果。 功能就是点击按钮&#xff0c;后台处理数据&#xff0c;前台显示处理数据的变化&#xff0c;当然还可以对进度条进行美化和关闭的操作&#xff0c;等待后台处理完毕数据&#xff0c;然后自动关闭。…

OPENWRT路由配置IPV6公网访问

前提&#xff1a;已经拥有ipv6地址&#xff0c;不会配置ipv6的同学可以看我的上一篇文章。 一、光猫配置 1.1、修改光猫连接方式变为桥接&#xff1a; 其中需要注意的点为&#xff1a; 1.需要将原先的xxxx_VID_41的连接删掉&#xff0c;然后按照下面的配置进行 2.删掉之前…

相关性分析和作图

相关的类型 1. Pearson、Spearman和Kendall相关 Pearson 积差相关系数衡量了两个定量变量之间的线性相关程度。&#xff08;连续&#xff09; Spearman等级相关系数则衡量分级定序变量之间的相关程度。&#xff08;分类&#xff09; Kendall’s Tau 相关系数也是一种非参数的…