通俗易懂的dagger2-入门篇

来源:互联网 发布:练瑜伽的软件 编辑:程序博客网 时间:2024/05/17 20:42

1. 什么是Dagger

一个Android和java快速依赖注射器。

1.1 关于Dagger

Dagger 2是依赖注入的编译时进化方法。 采用Dagger 1.x开始的方法达成最终结论,Dagger 2.x消除了所有的反射,并通过删除传统的ObjectGraph / Injector来改善代码清晰度,有利于用户指定的@Component接口。

这个github项目代表了Dagger 2开发流。 较早的项目页面(Square,Inc的存储库)代表较早的1.0开发流。 这两个版本都受益于Square,Google和其他贡献者的强烈参与。

Dagger 2目前正在积极发展,主要是内部在 Google,定期推动开源社区。 快照版本将自动部署到sonatype的中央maven存储库,每个干净的版本与版本HEAD-SNAPSHOT。

官网原文:
Dagger 2 is a compile-time evolution approach to dependency injection. Taking the approach started in Dagger 1.x to its ultimate conclusion, Dagger 2.x eliminates all reflection, and improves code clarity by removing the traditional ObjectGraph/Injector in favor of user-specified @Component interfaces.

This github project represents the Dagger 2 development stream. The earlier project page (Square, Inc’s repository) represents the earlier 1.0 development stream. Both versions have benefitted from strong involvement from Square, Google, and other contributors.

Dagger is currently in active development, primarily internally at Google, with regular pushes to the open-source community. Snapshot releases are auto-deployed to sonatype’s central maven repository on every clean build with the version HEAD-SNAPSHOT.

1.2 为什么Dagger 2是不同的

依赖注入框架已经存在多年,具有用于配置和注入的各种API。那么,为什么要重新发明轮?Dagger 2是第一个用生成的代码实现完整堆​​栈的。指导原则是生成模仿用户可能手写的代码的代码,以确保依赖注入是可以简单,可追溯和执行的。

官网原文:
Dependency injection frameworks have existed for years with a whole variety of APIs for configuring and injecting. So, why reinvent the wheel? Dagger 2 is the first to implement the full stack with generated code. The guiding principle is to generate code that mimics the code that a user might have hand-written to ensure that dependency injection is as simple.


2. 使用Dagger 2

因为现在android studio 3.0在测试,基本上都是使用as 2.3.3就无需再加入插件了,直接在appbuild.gradledependencies 中加入依赖就可以开始使用了。

2.1 添加依赖

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

x是版本号,目前最新的是2.11,查看最新版

2.2 常用注解

2.2.1 @Inject

用于告诉Dagger2,我们需要这个类的实例对象。主要用于标记哪个类是需要注入的,可标注在对象或方法上,不能标记private修饰的。

2.2.2 @Module

用于对外提供对象,一般可在@Module标注的类中添加自定义方法,方法标注@Provides,方法体中可用来做一些实例化操作等。

2.2.3 @Provides

配合@Module一起使用,@Provides用于标记方法,表示可以通过这个方法获取一个对象,一般用于自定义类中。

2.2.4 @Component

主要用于关联@Module标注的类和Activity及Fragment的子类。

2.2.5 @Named 和 @Qualifier

用于区别不同对象的实例,必须要成对出现。@Named是以自己定义的字符串去识别,@Qualifier是以注解类(@interface)去识别。

2.2.6 @Singleton

dagger 2中的单例模式,@Module类中使用了,@Component中也要使用。

2.2.7 @scope

Scopes可是非常的有用,Dagger2可以通过自定义注解限定注解作用域。这个注解我也不太熟悉,具体可以参考网络或官网。

3. 举个栗子

先拿一个简单的网络请求依赖注入。
整个包的结构最重要的就是 di 包下两个,network 包下是封装的一个简单的 retrofit 2.0 网络请求
structure.png

为了快速的看懂module和component中的代码,我们先看看network包下的代码,上代码
ApiService.class
RetrofitClient.clss

贴心代码

------ApiService.class------@GET("data/{type}/{count}/{page}")Observable<ResponseBody> getGank(@Path("type") String type,                                 @Path("count") int count,                                 @Path("page") int page);}------RetrofitClient.class------/** * 请求超时时间 */private static final long DEFAULT_TIMEOUT = 10 * 1000;/** * 服务器地址url */private static final String BASE_URL = "http://gank.io/api/";private static ApiService sApiService;public static ApiService getDefault() {    if (null == sApiService) {        synchronized (RetrofitClient.class) {            if (null == sApiService) {                OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()                        //设置超时时间                        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)                        .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)                        .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);                sApiService = new Retrofit.Builder()                        .client(httpClientBuilder.build())                        .addConverterFactory(GsonConverterFactory.create())                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                        .baseUrl(BASE_URL)                        .build().create(ApiService.class);            }        }    }    return sApiService;}

好了,一个超普通的 retrofit 请求封装。下面再看看 NetworkModule.class
NetworkModule.class

想必看也看得懂吧,一个类被标记 @Module 提供一个@Provides标记的方法,providesApiService()用于返回一个retrofit实例。代码就不贴出来了,多敲敲就会了 (=^ ^=)

再来看看NetworkComponent.class,他相当于是一个连接器,连接activity子类module
NetworkComponent.class

**注意:**inject()中参数不能写Activity,否则会报空指针。

马上就快完成了,在 MainActivity.class 中注入
MainActivity.clss

对象 ApiService 通过 @Inject 注入,DaggerNetworkComponent 是由系统生成的(as菜单栏BuildRebuild Project),如果找不到 DaggerNetworkComponent 就是你写错了,具体看log信息。


4. 结尾

在@Component中有一个dependencies,可以理解为依赖。过几天我会写一个dagger2在mvp中应用的博客,会把dagger的基础使用都写上,谢谢大家 (=^ ^=)
我的博客:https://wz1509.github.io/

原创粉丝点击