通俗易懂的dagger2-入门篇

1 什么是Dagger

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

1.1 关于Dagger

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

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

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

官网原文:
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.api

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.bash

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.app


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能够经过自定义注解限定注解做用域。这个注解我也不太熟悉,具体能够参考网络或官网。

2.3 举个栗子

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

structure.png
structure.png

为了快速的看懂module和component中的代码,咱们先看看network包下的代码,上代码

ApiService.class
ApiService.class

RetrofitClient.clss
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
NetworkModule.class

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

再来看看NetworkComponent.class,他至关因而一个链接器,链接activity子类module

NetworkComponent.class
NetworkComponent.class

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

立刻就快完成了,在 MainActivity.class 中注入

MainActivity.clss
MainActivity.clss

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


结尾:
在@Component中有一个dependencies,能够理解为依赖。过几天我会写一个dagger2在mvp中应用的博客,会把dagger的基础使用都写上,谢谢你们 (=^ ^=)

相关文章
相关标签/搜索