近日,GitHub遭遇史上最大规模DDoS攻击,每秒1.35TB的流量瞬间冲击了这一开发者平台。GitHub试图反抗,但不到10分钟,它就自动要求安全公司Akamai Prolexic提供帮助。这家专门减轻 DDoS 攻击的公司接管了 GitHub 的所有流量。它的服务器能够承受比普通站点大得多的流量,通过其清理中心发送数据以清除和阻止恶意数据包。这并不是第一次针对GitHub的重大DDoS攻击,该平台曾在2015年3月面临六天的冲击。
大家周一好,经过了元宵节的调整之后,将精力重新投入到工作中吧。
本篇来自 志先生_ 的投稿,分享了 Dagger2 的使用 ,一起来看看!希望大家喜欢。
志先生_ 的博客地址:
http://blog.csdn.net/gg199402
最近在做项目中,用到了 Dagger2,所以找了一些博客并参考了菜鸟窝 Ivan 的视频,算是知道如何使用了,但是对其理解还相差很远。所以这篇文章重点针对如何使用和使用中常见的一些问题。
根据官网来说他就是一个快速的依赖注入框架。如果对依赖注入不太了解,那么请自行搜索依赖注入原理,在这里我就不过多介绍了。其实他的作用重点就是解耦和管理实例对象。那我们看看他具体有什么好处:
依赖的注入和配置独立于组件之外,注入的对象在一个独立、不耦合的地方初始化,这样在改变注入对象时,我们只需要修改对象的实现方法,而不用大改代码库。
依赖可以注入到一个组件中:我们可以注入这些依赖的模拟实现,这样使得测试更加简单。
app 中的组件不需要知道有关实例创建和生命周期的任何事情,这些由我们的依赖注入框架管理的
这是网上的一切说法。对于文字我们不好理解,还是看看在具体应用中我们该如何去使用。不过在使用之前我们先简单的理解及概念。
@Inject
通常在需要依赖的地方使用这个注解。换句话说,你用它告诉 Dagger 这个类或者字段需要依赖注入。这样,Dagger 就会构造一个这个类的实例并满足他们的依赖。
@Module
Modules 类里面的方法专门提供依赖,所以我们定义一个类,用@Module 注解,这样 Dagger 在构造类的实例时候,就知道从哪里去找到需要的依赖。modules 的一个重要特征是它们设计为分区并组合在一起(比如说,我们的 app 中可以有多个组成在一起的modules)
@Provide
在 modules 中,我们定义的方法是用这个注解,以此来告诉 Dagger 我们想要构造对象并提供这些依赖。
@Component
Components 从根本上来说就是一个注入器,也可以说是@Inject 和@Module 的桥梁,它的主要作用就是连接这两个部分。
读不懂也没关系,我们接下来实战代码。在讲解后在结合概念我们就能很好的理解了。
引入方法有2种:
第一种
在工程的 build.gradle 文件中添加 android-apt 插件(该插件后面介绍)
buildscript {
....
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
// 添加android-apt 插件
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
在 app 的中的 build.gradle 文件中添加配置
apply plugin: 'com.android.application'
// 应用插件
apply plugin: 'com.neenbedankt.android-apt'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.mahao.alex.architecture"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
// dagger 2 的配置
compile 'com.google.dagger:dagger:2.4'
apt 'com.google.dagger:dagger-compiler:2.4'
compile 'org.glassfish:javax.annotation:10.0-b28'// 添加java 注解库
}
以上两个配置就可以了。
android-apt 是 Gradle 编译器的插件,根据其官方文档,主要两个目的:
编译时使用该工具,最终打包时不会将该插件打入到 apk 中。
能够根据设置的源路径,在编译时期生成相应代码。
在导入类库时,
compile 'com.google.dagger:dagger:2.4'
apt 'com.google.dagger:dagger-compiler:2.4'
dagger是主要的工具类库。dagger-compiler为编译时期生成代码等相关的类库。
在android-apt的文档中,也推荐使用这种方式。因为,编译时期生成代码的类库在运行期并不需要,那么将其分为两个库,(运行类库 dagger )和(编译器生成代码类库(dagger-compiler)),那么在打包时,就不需要将 dagger-compiler 打入其中(用不到),减小 APK 的大小。
第二种
这种方法比较简单(Android Studio2.2以上),直接引入依赖
compile 'com.google.dagger:dagger:2.9'
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
我们这里推荐第一种方式。
public class ApiService {
public void register() {
//注册的方法
Log.i("TAG", "ApiService: ");
}
}
public class UserStroe {
public void login(){
//登录的方法
}
}
首先假设我们现在有两个方法,一个是注册,另一个是登录。如果我们现在 MainActivity 中调用 register(); 我们一般会这么写:
ApiSeivie apiServce=new ApiService();
apiService.register();
如果们们使用Dagger2该如何使用呢?
Module
首先:我们先创建module(他是主要提供实例的类),这里我们定义为UserModule:
@Module
public class UserModule {
public UserModule() {
}
@Provides
public ApiService provideApiService() {
return new ApiService();
}
}
@Module
Modules 类里面的方法专门提供依赖,所以我们定义一个类,用@Module 注解,这样 Dagger 在构造类的实例时候,就知道从哪里去找到需要的依赖。
@Provide
在modules中,我们定义的方法是用这个注解,以此来告诉Dagger我们想要构造对象并提供这些依赖。
现在我们回头在看看概念是不就明白其中的含义了。
可以看到我们在 MainActivity 中需要 ApiService,我们在 module 中创建他的实例。等他需要的时候我们就给他。现在 module 创建好了。我们还需要调用者( MainActivity )和被调用者( module )之间的桥梁,这就是 Component。
@Component(modules = {UserModule.class})
public interface UserComponet {
void inject(MainActivity activity);
}
我们定义 UserComponet 并加上@Component 注解。表明他是一个桥梁。首先他必须是一个接口。其次我们必须依赖一个 module(当然,从{}这个符号我们就可以看到,他可以同时依赖多个 module),它还有另一参数 dependencies,这里我们先不说他,等后面讲到了再说他。这里我们看到他里面只有一个方法 void inject()。这里我们传入 MainActivity,因为我们想在这个类中使用我们实例 ApiService。这样 module 和 MainActivity 通过 Component 就关联起来了。创建好这些类以后我们需要 Rebuild Progect。
这是会生成一个 DaggerUserComponet 类,这个类命名是以 Dagger 开头接上我们 UserComponet 类名。这个类方法很少,主要就是将我们的 MainActivity 和 Component 关联起来,通过:
DaggerUserComponet.create().inject(this);
将我们的 MainActivity 传入 Component 的 inject()方法中,这样这个桥梁就就通了,我们就可以使用了,如下:
public class MainActivity extends AppCompatActivity {
@Inject
ApiService mApiService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerUserComponet.create().inject(this);
mApiService.register();
Log.d("TAG", "onCreate: " + mApiService);
}
}
dagger2 D/TAG: ApiService:
com.example.ggxiaozhi.dagger2 D/TAG: onCreate: com.example.ggxiaozhi.dagger2.ApiService@4a7c73b4
可以看到正常运行没有问题了。实例对象已经被我们创建出来了。为们用2张图总结一下:
这张图从概念出发,我们再从我们的例子中总结出来经验概括就是这样的:
明白了流程后那他是怎么解耦的呢?使用方法就这么简单就结束了吗?答案是肯定的。我们一定不止这么简单,关于解耦的话我就举一个简单的例子。之前我们创建了2个类注册和登录,现在我们再创建一个类去管理他们:
public class UserManager {
UserStroe mUserStroe;
ApiService mApiService;
public UserManager() {
mApiService = new ApiService();
mUserStroe = new UserStroe();
}
public void register() {
mApiService.register();
mUserStroe.login();
}
}
然后我们在 MainActivity 中去调用 UserManager 中的 register 方法。这么一个看好像是没什么问题,但是如果我们 mApiService.register(); 需要一个 Context 参数怎么办?你可能会这么该:
public class UserManager {
UserStroe mUserStroe;
ApiService mApiService;
public UserManager(Context context) {
mApiService = new ApiService(context);
mUserStroe = new UserStroe();
}
public void register() {
mApiService.register();
mUserStroe.login();
}
}
调用处 new UserManager(this); 但是你注意看,我们只是需要一个 context 就要将 UserManager 和 MainActivity 中的代码都要改,要是在实际项目中,需要改更多的参数呢?所以我们来看下用 Dagger2 该如何解决。这里我把需求再复杂话一些。首先我们还是先从module 来看: 这里我们将例子复杂一下假设 ApiService 需要一个 context,userStroe 需要一个 url。我们就可以这样写
@Module
public class UserModule {
Context context;
public UserModule(Context context) {
this.context = context;
}
@Provides
public ApiService provideApiService() {
return new ApiService(context);
}
@Provides
public String providerUrl() {
return "www.baidu.com";
}
@Provides
public UserManager provideUserManager(ApiService apiService, UserStroe userStroe) {
return new UserManager(userStroe, apiService);
}
}
public class UserManager {
UserStroe mUserStroe;
ApiService mApiService;
public UserManager(UserStroe mUserStroe, ApiService mApiService) {
this.mUserStroe = mUserStroe;
this.mApiService = mApiService;
}
public void register() {
mApiService.register();
mUserStroe.login();
}
}
public class UserStroe {
@Inject
public UserStroe(String url) {
Log.d("TAG", "UserStroe: " + url);
}
public void login() {
Log.d("TAG", "UserStroe: ");
}
}
public class MainActivity extends AppCompatActivity {
@Inject
UserManager mManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerUserComponet.builder().userModule(new UserModule(this)).build().inject(this);
mManager.register();
Log.d("TAG", "onCreate: " + mManager);
}
}
这里我们创建 DaggerUserComponet 用了方法:
DaggerUserComponet.builder().userModule(new UserModule(this)).build().inject(this);
这个方法与之前用的其实内部都是一样的,因为我们 UserModule 需要 context 参数,所以我们选择这种构建方法。
可以看到在创建对象时我们可以在 module 中像之前一样提供一个创建的方法,第二种我们也可以通过在对象的构造函数上加上@Inject 注解,这里我们需要一个 url 和 context,我们只需要提供一个创建 String 的 url 方法即可,并通过 UserModule 的构造函数将 conetxnt 传入,最后提供一个创建 UserManager 的方法将两个参数穿进去,最后运行一下:
dagger2 D/TAG: UserStroe: www.baidu.com
com.example.ggxiaozhi.dagger2 D/TAG: ApiService:
com.example.ggxiaozhi.dagger2 D/TAG: UserStroe:
com.example.ggxiaozhi.dagger2 D/TAG: onCreate: com.example.ggxiaozhi.dagger2.UserManager@4a7c6f00
上面在学习了 Dagger2 的基本用法后下面我们来看下它的高级用法。
注解
@Qualifier: 要作用是用来区分不同对象实例
@Named 其实是@Qualifier 的一种实现
Scope
Subcomponent
Lazy与Provider
@Qualifier
上面也提到了,作用是用来区分不同对象的实例的。平时我们可能会对一个类创建不同的构造方法以满足不同的需求,假设现在现在 ApiSevice 有2个构造方法,根据不同情况调用不同方法。这时就要用到@Named 标签(@Named 是@Qualifier 的一种实现)
public class ApiService {
public ApiService(Context context) {
}
public ApiService(String url) {
Log.d("TAG", "ApiService: " + url);
}
public void register() {
Log.d("TAG", "ApiService: ");
}
}
可以看到 ApiService 有2个不同的构造方法,并且参数不同。下面我们就要在 UserModule分别创建这两个对象的实例。
@Module
public class UserModule {
Context context;
public UserModule(Context context) {
this.context = context;
}
@Provides
@Named("dev")
public ApiService provideApiServiceDev(String url) {
ApiService apiService = new ApiService(url);
Log.d("TAG", "provideApiServiceDev: " + apiService);
return apiService;
}
@Provides
@Named("release")
public ApiService provideApiServiceRelease() {
ApiService apiService = new ApiService(context);
Log.d("TAG", "provideApiServiceRelease: " + apiService);
return apiService;
}
@Provides
public Context provideContext() {
return context;
}
@Provides
public String providerUrl() {
return "www.baidu.com";
}
@Provides
public UserManager provideUserManager(ApiService apiService, UserStroe userStroe) {
return new UserManager(userStroe, apiService);
}
}
可以看到我们为ApiService分别提供了2个构造方法但参数不同。然后分别用@Named(“dev”)和@Named(“release”)注解,表明这是2个不同的构造方法。
(提问:这里为什么我们可以直接引用参数参数中的 context 和 url 呢?因为我们提供了providerUrl() 和 provideContext() 所以可以直接使用)
那么我们看下 MainActivity 中如何调用的:
@Named("dev")
@Inject
ApiService mApiService;
@Named("release")
@Inject
ApiService mApiService1;
private boolean is_Dev = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerUserComponet.builder().userModule(new UserModule(this)).build().inject(this);
Log.d("TAG", "mApiService= " + mApiService);
Log.d("TAG", "mApiService1= " + mApiService1);
if (is_Dev) {
mApiService.register();
} else {
mApiService.register();
}
}
}
可以看到我们在 modle 中用@Named 区分,在使用是只需在 @Inject 时添加上@Named 注解就会创建对应注解的实例,然后我们用一个 is_Dev 标签,表明不同情况使用不同的对象。我们来看下打印结果:
D/TAG: ApiService: www.baidu.com
D/TAG: provideApiServiceDev: .ApiService@4a7c44c8
D/TAG: provideApiServiceRelease: .ApiService@4a7c477c
D/TAG: mApiService= .ApiService@4a7c44c8
D/TAG: mApiService= .ApiService@4a7c477c
@Qualifier
@Documented
@Retention(RUNTIME)
public @interface Named {
/** The name. */
String value() default "";
}
@Qualifier :注明是Qualifier(关键词)
@Documented :标记在文档
@Retention(RUNTIME) :运行时级别
可以看到@Qualifier决定它关键性的作用是用来区分不同对象的。里面的String类型就是我们之前填写的(“dev”)和(“release”)用来区分的,那么我也照着写我们的自定义的标签:
@Qualifier
@Retention(RUNTIME)
public @interface Dev {
}
@Qualifier
@Retention(RUNTIME)
public @interface Release {
}
我们创建了2个自定义注解,当然你全赋值过来也是没有问题的,这里我去掉了不必要的部分。因为本身我们就不像用字符串区分了,所以我把字符串参数去掉了。
@Provides
@Release
public ApiService provideApiServiceDev(String url) {
ApiService apiService = new ApiService(url);
Log.d("TAG", "provideApiServiceDev: " + apiService);
return apiService;
}
@Provides
@Dev
public ApiService provideApiServiceRelease() {
ApiService apiService = new ApiService(context);
Log.d("TAG", "provideApiServiceRelease: " + apiService);
return apiService;
}
@Dev
@Inject
ApiService mApiService;
@Release
@Inject
ApiService mApiService1;
用法和上面是结果是一样的。
@Singleton
我们先看下他的里面是什么样子的:
@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {}
友情提示:我刚学习的时候就总搞不懂总以为@Scope,@Singleton,@Qualifier,@Named 是4个不同作用的操作符,其实他就是两两一对的,@Named 是@Qualifier 具体实现,@Singleton 是@Scope 的具体实现;@Scope 和@Qualifier 类似不同作用注解的关键字
他就是用@Scope 注解修饰的注解。这样我们就知道了。那么首先我们来看下,如果不用单例什么样的:
@Inject
ApiService mApiService1;
@Inject
ApiService mApiService2;
private boolean is_Dev = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerUserComponet.builder().userModule(new UserModule(this)).build().inject(this);
Log.d("TAG", "mApiService1= " + mApiService1);
Log.d("TAG", "mApiService2= " + mApiService2);
}
}
结果:
D/TAG: mApiService1= .ApiService@4a7c7904
D/TAG: mApiService2= .ApiService@4a7c7aa8
可以看到确实创建了2个实例,那么如何使用单例注解:
首先在 Module 中将创建实例的方法加上@Singleton
@Singleton
@Provides
public ApiService provideApiService() {
ApiService apiService = new ApiService(context);
Log.d("TAG", "provideApiService: " + apiService);
return apiService;
}
然后在@Component中也加上@Singleton:
@Singleton
@Component(modules = {UserModule.class})
public interface UserComponet {
void inject(MainActivity activity);
}
@Singleton在使用时调用处正常书写:
@Inject
ApiService mApiService1;
@Inject
ApiService mApiService2;
打印结果:
provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7c5200
mApiService1= com.example.ggxiaozhi.dagger2.ApiService@4a7c5200
mApiService2= com.example.ggxiaozhi.dagger2.ApiService@4a7c5200
可以看到只调用了一次创建对象的方法。2个对象其实是一个实例。
注意:
module 的 provide 方法使用了 scope ,那么 component 就必须使用同一个注解
@Singleton 的生命周期依附于 component,同一个 module 被不同的@Component 依赖结果也不一样 @Singleton 分为 Activity 级别单例生命周期和全局的生命周期单例
这里第一点注意我们通过上面的事例比较容易理解,那么第二点是什么意思呢?这句话的意思在于@Singleton 的生命周期依附于 component。那么实际测试下。我们在创建一个 LoginAcyivity。并创建 LogingConponent 如下:
@Singleton
@Component(modules = UserModule.class)
public interface LoginComponent {
void inject(LoginActivity activity);
}
LogingConponent 也依赖 UserModule.class。然后在 LoginAcyivity 中创建 ApiService 如下:
public class LoginActivity extends AppCompatActivity {
@Inject
ApiService mApiService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
DaggerLoginComponent.builder().userModule(new UserModule(this)).build().inject(this);
Log.d("TAG", "LoginActivity-->mApiService : "+mApiService);
}
}
运行结果:
D/TAG: provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7c5994
D/TAG: MainActivity-->mApiService1= com.example.ggxiaozhi.dagger2.ApiService@4a7c5994
D/TAG: MainActivity-->mApiService2= com.example.ggxiaozhi.dagger2.ApiService@4a7c5994
D/TAG: provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7d54f8
D/TAG: LoginActivity-->mApiService : com.example.ggxiaozhi.dagger2.ApiService@4a7d54f8
可以看你到 LoginComponent 和 UserComponent 都依赖 UserMoudle,并且创建ApiService 已经加了@Singleton注解但是在 MainActivity 中是单例但是在 LoginActivity 又创建了不同的 ApiService 的实例,这就是上面提到的因为 LoginComponent 和UserComponent 为两个不同的@Component,@Singleton的生命周期依附于 component同一个 module provide singleton ,不同 component 也是不一样。所以会看到这样的结果。如果我们修改下代码呢?如下:
@Singleton
@Component(modules = {UserModule.class})
public interface UserComponet {
void inject(MainActivity activity);
void inject(LoginActivity activity);
}
然后在 LoginActivity 中也引用 UserComponent 而不去引用 LogingComponent 呢?
public class LoginActivity extends AppCompatActivity {
@Inject
ApiService mApiService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
UserComponet userComponet = DaggerUserComponet.builder().userModule(new UserModule(this)).build();
userComponet.inject(this);
Log.d("TAG", "LoginActivity-->mApiService : "+mApiService);
Log.d("TAG", "LoginActivity-->UserComponet : "+userComponet);
}
}
这也也是不行的。为什么?看打印结果:
D/TAG: provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7c454c
D/TAG: MainActivity-->mApiService1= com.example.ggxiaozhi.dagger2.ApiService@4a7c454c
D/TAG: MainActivity-->mApiService2= com.example.ggxiaozhi.dagger2.ApiService@4a7c454c
D/TAG: MainActivity-->UserComponet= com.example.ggxiaozhi.dagger2.DaggerUserComponet@4a7c382c
D/TAG: provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7d3ccc
D/TAG: LoginActivity-->mApiService : com.example.ggxiaozhi.dagger2.ApiService@4a7d3ccc
D/TAG: LoginActivity-->UserComponet : com.example.ggxiaozhi.dagger2.DaggerUserComponet@4a7d3c9c
可以看到,在 UserComponet 在 LoginActivity和 MainActivity 中会创建2个不同的实例,当然会创建2个不同的 mApiService 了。如果像实现全局单例我就就要用到自定义@Scope注解。
自定义@Scope注解
上面是属于Activity生命周期单例。下面我们就创建全局生命周期单例。
@Module
public class AppMoudle {
private MyApplication context;
public AppMoudle(MyApplication context) {
this.context = context;
}
@Singleton
@Provides
public ApiService provideApiService() {
ApiService apiService = new ApiService(context);
Log.d("TAG", "provideApiService: " + apiService);
return apiService;
}
}
@Singleton
@Component(modules = AppMoudle.class)
public interface AppComponent {
/**
* 全局单例。所以不用Inject Activity
*
* @return 向下返回ApiService实例
*/
ApiService getApiService();
}
单例的依托于他所在的 Component 中,所以需要在 Application 中进行实例化。
public class MyApplication extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerAppComponent.builder().appMoudle(new AppMoudle(this)).build();
}
public AppComponent getAppComponent() {
return mAppComponent;
}
}
@Scope
@Retention(RUNTIME)
public @interface PerActivity {
}
@PerActivity
@Component(modules = {UserModule.class},dependencies = AppComponent.class)
public interface UserComponet {
void inject(MainActivity activity);
}
@PerActivity
@Component(modules = UserModule.class,dependencies = AppComponent.class)
public interface LoginComponent {
void inject(LoginActivity activity);
}
DaggerUserComponet.builder().
appComponent(((MyApplication)getApplicationContext()).getAppComponent()).
build().inject(this);
LoginActivity
DaggerLoginComponent.builder().
appComponent(((MyApplication)getApplicationContext()).getAppComponent()).
build().inject(this);
D/TAG: provideApiService: com.example.ggxiaozhi.dagger2.ApiService@4a7c3e8c
D/TAG: MainActivity-->mApiService1= com.example.ggxiaozhi.dagger2.ApiService@4a7c3e8c
D/TAG: MainActivity-->mApiService2= com.example.ggxiaozhi.dagger2.ApiService@4a7c3e8c
D/TAG: LoginActivity-->mApiService= com.example.ggxiaozhi.dagger2.ApiService@4a7c3e8c
可以看到这次全局都是用的一个单例了。
我们用代码使用体会下:
FComponent
//第一步
@Module
public class FModule {
@Singleton
@Provides
public User provideUser() {
return new User();
}
}
//第二步
@Singleton
@Component(modules = FModule.class)
public interface FComponent {
//需要将SubComponent 追加到被依赖的Component中
CComponent addCComponent();
}
//第三步
public class MyApplication extends Application {
private AppComponent mAppComponent;
private FComponent mFComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerAppComponent.builder().appMoudle(new AppMoudle(this)).build();
mFComponent = DaggerFComponent.builder().build();
}
public AppComponent getAppComponent() {
return mAppComponent;
}
public FComponent getFComponent() {
return mFComponent;
}
}
CComponent
@Module
public class CModule {
@PerActivity
@Provides
public UserStroe provideUser(User user) {
return new UserStroe(user);
}
}
@PerActivity
@Subcomponent(modules = CModule.class)
public interface CComponent {
void Inject(Main2Activity activity);
}
调用
public class Main2Activity extends AppCompatActivity {
private static final String TAG = "Main2Activity";
@Inject
UserStroe mUserStroe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
((MyApplication)getApplicationContext()).getFComponent().getCComponent().Inject(this);
Log.d(TAG, "onCreate: "+mUserStroe);
}
}
首先我们先创建FComponent,他属于App级别的。我们在MyApplication创建它。FComponent中调用者提供CComponent。然后有CComponent。这和我们之前使用有些不同。之前我们都是通过Avtivity级别创建,然后填入App级别的参数。这个使用正好相反。优势:
不需要在被依赖的Component显示提供依赖,不需要使用更多的DaggerXXXXComponent对象来创建依赖,仅需要在被依赖Component中增加 XXXComponent addXXComponent(XXXModule) 方法
这个如果不太理解也没有关系,会使用就行。
懒加载 Lazy 和强制重新加载 Provider
这个比较简单,我就列举一个简单的例子。
public class Container{
@Inject Lazy<User> lazyUser; //注入Lazy元素
@Inject Provider<User> providerUser; //注入Provider元素
public void init(){
DaggerComponent.create().inject(this);
User user1=lazyUser.get();
//在这时才创建user1,以后每次调用get会得到同一个user1对象
User user2=providerUser.get();
//在这时创建user2,以后每次调用get会再强制调用Module的Provides方法一次,
//根据Provides方法具体实现的不同,可能返回跟user2是同一个对象,也可能不是。
}
}
注意事项(重要)分析
componet 的 inject 方法接收父类型参数,而调用时传入的是子类型对象则无法注入
component 关联的 modules 中不能有重复的 provide
module 的 provide 方法使用了 scope ,那么 component 就必须使用同一个注解
module 的 provide 方法没有使用 scope ,那么 component 和 module 是否加注解都无关紧要,可以通过编译
component 的 dependencies 与 component 自身的 scope 不能相同,即组件之间的scope 不同
Singleton 的组件不能依赖其他 scope 的组件,只能其他 scope 的组件依赖 Singleton的组件
没有 scope 的 component 不能依赖有 scope 的 component
一个 component 不能同时有多个 scope ( Subcomponent 除外)
@Singleton 的生命周期依附于component,同一个 module provide singleton ,不同component 也是不一样
Component 注入的 Activity 在其他 Component 中不能再去注入
dagger2 是跟着生命周期的绑定 Activity(Fragment)onDestory 对象也会销毁
创建实例的方法和引用实例都不能用private修饰
刚开始使用一定总会遇到很多错误,遇到错误不要着急。如果注意事项中的错误没有犯的话一定会减少很多错误。
不知不觉写的有点多。对我这种菜鸟,看源码写博客。真的很费心,学过的技术忘的很快,很多东西理解不透彻,想把博客写好写深还是很有难度的。不过如果你看到了这篇文章,发现的问题请留言一起探讨。Dagger2 也是在我用 MVP 构建项目时候使用的,可能学习的不是很深入。不过相信把这两篇文章的代码敲一边。平常的使用一定没有问题的。最后希望大家一起加油!!!
欢迎长按下图 -> 识别图中二维码
或者 扫一扫 关注我的公众号