고급 아키텍처 원칙 및 세부의 Dagger2

디렉토리

  • A : Dagger2 무엇입니까?
  • 2 : 왜해야 Dagger2
  • 세 : Dagger2은 사용 방법
  1. 기본 개념
  2. Dagger2를 사용하는 방법
  3. 고급 사용법

경우 (1) 설계 방법은 모든 파라미터를 필요로
(2) 모듈 간의 의존성
(3) 주석 @Named
(4) @Singleton 주석
(5) 정의 범위가 지정된
. (6) 하위 구성
. (7) 및 지연 공급자

  • 네 : MVP + Dagger2

시 : 결국 건축가는 고급 데이터 및 정보 얼굴 질문

A : Dagger2 무엇입니까?

종속성 분사기구이고, butterknife 종속성 주입 프레임 워크이다. 그러나 butterknife, 대부분의 버터 나이프라고, Dagger2은 무기 아, 그의 주요 역할은 객체를 관리하는 것입니다라고, 그 목적은 커플 링 절차를 줄이는 것입니다.

2 : 왜해야 Dagger2

고급 아키텍처 원칙 및 세부의 Dagger2

지금은 손 것

public class A {
 public void eat() {
 System.out.print("吃饭了");
 }
}

우리는 시간을 사용합니다

A a = new A();
a.eat();

이제 변경 한 경우, 초기 생성자는 객체 B를 통과해야

 public class A {
 private B b;
 public A(B b) {
 this.b = b;
 }
 public void eat() {
 System.out.print("吃饭了");
 }
}

그래서 시간을 사용

A a = new A(new B());
a.eat();

어떤 사람들은 우리가이 생성자가 변경되었을 경우는 여기에, 나는 느낌은 매우 간단 참조 인용 매우 간단한 예이지만, 실제 개발에 객체를 추가하지 무엇을 말할 수 있습니다. 그 뜻, 전체 프로젝트가 변경, 실수, 버그 아

세 : Dagger2은 사용 방법

1. 기본 개념

당신까지 내가 특정 개체의 @Inject를 사용하여 단검을 훨씬 더 좋을 것이다,인지를 갖고 싶어 내려다보고, 몇 가지 개념을 설명하고자 여기에, 확실히 무지 힘을 재생하는 방법, 말을하고 그 또, @Provides 노트가 제공되지만, 음, @Provides 만 @Component @Module 노트, 우리가 발견, 모듈로 직접 이동하지 않지만 갔다 고정 모듈에

고급 아키텍처 원칙 및 세부의 Dagger2

우리가 사용할 때 우리는 역을 도출

@Inject
A a

想要获取a对象的示例的时候,Dagger2 会先去找,当前Activity或者Fragment所连接的桥梁,例如上图中,连接的只有一个桥梁,实际上可以有多个,这个桥梁,会去寻找他所依赖的模块,如图中,依赖了模块A,和模块B,然后在模块中,会去寻找@Providers注解,去寻找A的实例化对象。

2. 如何使用Dagger2

(1) 引入依赖库

Dagger2官网

compile 'com.google.dagger:dagger:2.11'
 annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
(2) 创建Moudule
//第一步 添加@Module 注解
@Module
public class MainModule {
}
(3)创建具体的示例
//第一步 添加@Module 注解
@Module
public class MainModule {
 //第二步 使用Provider 注解 实例化对象
 @Provides
 A providerA() {
 return new A();
 }
}
(4)创建一个Component
//第一步 添加@Component
//第二步 添加module
@Component(modules = {MainModule.class})
public interface MainComponent {
 //第三步 写一个方法 绑定Activity /Fragment
 void inject(MainActivity activity);
}
(5)Rebuild Project

고급 아키텍처 원칙 및 세부의 Dagger2

然后AS 会自动帮我们生成一个

고급 아키텍처 원칙 및 세부의 Dagger2

开头都是以Dagger开始的

(6)将Component与Activity/Fragment绑定关系
package com.allens.daggerdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.allens.daggerdemo.Bean.A;
import com.allens.daggerdemo.component.DaggerMainConponent;
import javax.inject.Inject;

public class MainActivity extends AppCompatActivity {
 /***
 * 第二步 使用Inject 注解,获取到A 对象的实例
 */
 @Inject
 A a;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 /***
 * 第一步 添加依赖关系
 */
 //第一种方式
 DaggerMainConponent.create().inject(this);

 //第二种方式
 DaggerMainConponent.builder().build().inject(this);

 /***
 * 第三步 调用A 对象的方法
 */
 a.eat();
 }
}

肯定有小伙伴说了,为了拿到一个对象,这么大个弯,太麻烦了。别急慢慢看,路要一步一步走嘛

3. 高级用法

(1)构造方法需要其他参数时候

怎么说呢,就和最来时的意思一样,

A a = new A(new B());
a.eat();

这种情况,如何使用Dagger2呢

肯定有小伙伴这么想

@Provides
 A providerA() {
 return new A(new B());
 }

直接 new 一个B ,这样的使用方法,是不对的!!!!!!,不对的!!!!!!!,不对的!!!!!!!!!

正确的打开方式

这时候,我们什么都不用该,只需要在moudule中添加一个依赖就可以了

@Module
public class MainModule {

 /***
 * 构造方法需要其他参数时候
 *
 * @return
 */
 @Provides
 B providerB() {
 return new B();
 }

 @Provides
 A providerA(B b) {
 return new A(b);
 }
}
(2) 模块之间的依赖关系

고급 아키텍처 원칙 및 세부의 Dagger2

模块与模块之间的联系,

@Module (includes = {BModule.class})// includes 引入)
public class AModule {
 @Provides
 A providerA() {
 return new A();
 }
}

这样的话,Dagger会现在A moudule 中寻找对象,如果没找到,会去找module B 中是否有被Inject注解的对象,如果还是没有,那么GG,抛出异常

一个Component 应用多个 module

@Component(modules = {AModule.class,BModule.class})
public interface MainComponent {
 void inject(MainActivity activity);
}

dependencies 依赖其他Component

@Component(modules = {MainModule.class}, dependencies = AppConponent.class)
public interface MainConponent {
 void inject(MainActivity activity);
}

注意 这里有坑。一下会讲解

(3) @Named注解使用

相当于有个表示,虽然大家都是同一个对象,但是实例化对象不同就不如

A a1 = new A();
A a2 = new A();

// a1 a2 能一样嘛

Module中 使用@Named注解

@Module
public class MainModule {

 private MainActivity activity;

 public MainModule(MainActivity activity) {
 this.activity = activity;
 }

 @Named("dev")
 @Provides
 MainApi provideMainApiDev(MainChildApi mainChildApi, String url) {
 return new MainApi(mainChildApi, activity,"dev");
 }

 @Named("release")
 @Provides
 MainApi provideMainApiRelease(MainChildApi mainChildApi, String url) {
 return new MainApi(mainChildApi, activity,"release");
 }

}

在Activity/Fragment中使用

public class MainActivity extends AppCompatActivity {

 @Named("dev")
 @Inject
 MainApi apiDev;

 @Named("release")
 @Inject
 MainApi apiRelease;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 DaggerMainComponent.builder()
 .mainModule(new MainModule(this))
 .mainChildModule(new MainChildModule())
 .build()
 .inject(this);
 apiDev.eat();
 apiRelease.eat();
 Log.i("TAG","apiDev--->" + apiDev);
 Log.i("TAG","apiRelease--->" + apiRelease);
 }

}

打印Log

07-14 01:46:01.170 2006-2006/? I/TAG: apiDev--->com.allen.rxjava.MainApi@477928f
07-14 01:46:01.170 2006-2006/? I/TAG: apiRelease--->com.allen.rxjava.MainApi@f2b291c
(4) @Singleton注解

单利模式,是不是超级方便,你想然哪个对象单利化,直接在他的Provider上添加@Singleton 就行了

例如

@Singleton
 @Provides
 A providerA(B b) {
 return new A(b);
 }

注意: 第一个坑!!!
如果 moudule所依赖的Comonent 中有被单利的对象,那么Conponnent也必须是单利的

@Singleton
@Component(modules = {MainModule.class})
public interface MainConponent {
}

然后 在Activity中使用,直接打印a1 a2 的地址,

@Inject
 A a2;
 @Inject
 A a1;

可以看到Log

12-30 01:32:58.420 3987-3987/com.allens.daggerdemo E/TAG: A1---->com.allens.daggerdemo.Bean.A@11fa1ba
12-30 01:32:58.420 3987-3987/com.allens.daggerdemo E/TAG: A1---->com.allens.daggerdemo.Bean.A@11fa1ba

不相信的小伙伴可以吧@Singleton去掉试试

现在我们完成了单利,然后做了一个事情,就是点击某个按钮,跳转到一个新的Activiry,两边都引用同样一个A 对象,打印A 的地址,

说一下,一个Conponent 可以被对个Activity/Fragment 引用,如

@Singleton
@Component(modules = {MainModule.class})
public interface MainConponent {
 void inject(MainActivity activity);
 void inject(TestAct activity);
}

上面与两个Activity, MainActivity 和 TestAct ,都引用相同的 对象,答应地址看看

12-30 00:48:17.477 2788-2788/com.allens.daggerdemo E/TAG: A1---->com.allens.daggerdemo.Bean.A@11fa1ba
12-30 00:48:17.517 2788-2788/com.allens.daggerdemo E/TAG: A2---->com.allens.daggerdemo.Bean.A@4f81861

竟然不同,说好的单利呢

注意: 第二个坑,单利对象只能在同一个Activity中有效。不同的Activity 持有的对象不同

那有人就要问了,没什么办法么,我就想全局只要一个实例化对象啊? 办法肯定是有的,

(5) 自定义Scoped
/**
 * @作者 : Android架构
 * @创建日期 :2017/7/14 下午3:04
 * @方法作用:
 * 参考Singleton 的写法
 * Scope 标注是Scope
 * Documented 标记在文档
 * @Retention(RUNTIME) 运行时级别
 */
@Scope
@Documented
@Retention(RUNTIME)
public @interface ActivityScoped {
}

首先想一下,什么样的对象,能够做到全局单例,生命周期肯定和APP 绑定嘛,这里我做演示,一个AppAip 我们要对这个对象,全局单利,所以二话不说,先给Application 来个全家桶,

Module

@Module
public class AppModule {

 @Singleton
 @Provides
 AppApi providerAppApi() {
 return new AppApi();
 }
}

Component

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
 AppApi getAppApi();
}

Application

public class MyApp extends Application {

 private AppConponent appComponent;

 @Override
 public void onCreate() {
 super.onCreate();
 appComponent = DaggerAppConpoment.create();
 }

 public AppConponent getAppComponent() {
 return appConponent;
 }
}

最后是如何使用

首先,这个是个桥梁,依赖方式,上文已经说过了

@ActivityScoped
@Component(modules = {MainModule.class}, dependencies = AppConponent.class)
public interface MainComponent {
 void inject(MainActivity activity);
 void inject(TestAct activity);
}

细心的小伙伴可能已经发现了,只有在上面一个MainComponent添加了一个@ActivityScoped,这里说明一下,@Singleton是Application 的单利

注意,第三个坑,子类component 依赖父类的component ,子类component的Scoped 要小于父类的Scoped,Singleton的级别是Application

所以,我们这里的@Singleton 级别大于我们自定义的@ActivityScoped,同时,对应module 所依赖的component ,也要放上相应的Scope

好吧,上面的例子,打印Log.

12-30 02:16:30.899 4717-4717/? E/TAG: A1---->com.allens.daggerdemo.Bean.AppApi@70bfc2
12-30 02:16:31.009 4717-4717/? E/TAG: A2---->com.allens.daggerdemo.Bean.AppApi@70bfc2

一样啦

爬坑指南(极度重要)

  1. Provide 如果是单例模式 对应的Compnent 也要是单例模式
  2. inject(Activity act) 不能放父类
  3. 即使使用了单利模式,在不同的Activity 对象还是不一样的
  4. 依赖component, component之间的Scoped 不能相同
  5. 子类component 依赖父类的component ,子类component的Scoped 要小于父类的Scoped,Singleton的级别是Application
  6. 多个Moudle 之间不能提供相同的对象实例
  7. Moudle 中使用了自定义的Scoped 那么对应的Compnent 使用同样的Scoped
(6)Subcomponent

这个是系统提供的一个Component,当使用Subcomponent,那么默认会依赖Component

例如

@Subcomponent(modules = TestSubModule.class)
public interface TestSubComponent {
 void inject(MainActivity activity);
}
@Component(modules = {MainModule.class})
public interface MainConponent {
 TestSubComponent add(TestSubModule module);
}

在TestSubComponent中 我void inject(MainActivity activity);,便是这个桥梁,我是要注入到MainActivity,但是dagger 并不会给我生成一个Dagger开头的DaggerTestSubComponent 这个类,如果我想使用TestSubModule.class里面提供的对象,依然还是使用DaggerMainConponent例如

DaggerMainConponent
 .builder()
 .mainModule(new MainModule())
 .build()
 .add(new TestSubModule())
 .inject(this);

可以看到这里有一个add的方法,真是我在MainConponent添加的TestSubComponent add(TestSubModule module);

(7)lazy 和 Provider
public class Main3Activity extends AppCompatActivity {

 @PresentForContext
 @Inject
 Lazy<Present> lazy;
 @PresentForName
 @Inject
 Provider<Present> provider;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main3);

 AppComponent appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
 ActivityComponent activityComponent = DaggerActivityComponent.builder()
 .appComponent(appComponent)
 .activityModule(new ActivityModule())
 .build();

 activityComponent.injectActivity(this);
 Present present = lazy.get();
 Present present1 = provider.get();
 }
}

其中Lazy(懒加载)的作用好比component初始化了一个present对象,然后放到一个池子里,需要的时候就get它,所以你每次get的时候拿到的对象都是同一个;并且当你第一次去get时,它才会去初始化这个实例.

procider(强制加载)的作用:

1:同上当你第一次去get时,它才会去初始化这个实例

2:后面当你去get这个实例时,是否为同一个,取决于他Module里实现的方式

네 : MVP + Dagger2

이 디자인 아키텍처는 현재 주류

MVP, 나는 여기에 설명을 너무 많이하지 않는다,이 문서에 대해 설명 뒷면에있을거야

당신이 MVP를 이해하면, 모든 모든 비즈니스 로직에서 발표자를 알고

개체를 보유 발표자 즉, 단검, 우리는 그냥 모든 presetner 제어 객체에 분명하게 말을하는 프로그램의 전체 논리를 제어

단순히 참고로, 물론, 디렉토리 구조 아래 첨부. 난 그냥 프로젝트의 단검을 알았을 때 단검 강력한 사용하거나 자신의 경험을 필요는 다음과 같은 항목이 작성됩니다
고급 아키텍처 원칙 및 세부의 Dagger2

고급 아키텍처 원칙 및 세부의 Dagger2

당신은 내가하는 모든 활동이다 또는 조각이 동일한 구성 요소에 모두 추가를 볼 수 있습니다, 물론 지금은 권장하지 않을 경우, 예를 들어 당신이 구성 요소를 전문으로 할 수 유틸,

우선이 모듈을 넣어,이 회사는 Presneter의 시작 페이지를, 나는 SplashPresenter 여기에서 볼 수있는, 많은 것들을 이해, 감동을 감히하지 않았다, 비즈니스 로직을한다 프로젝트

@Module
public class ApiModule {

 public ApiModule() {

 }

 @Provides
 @Singleton
 Handler provideHandler() {
 return new Handler();
 }

 @Provides
 @Singleton
 SQLiteDatabase provideSQLiteDatabase() {
 return new DataBaseHelper(MyApp.context, Config.SqlName, null, Config.SqlVersion).getWritableDatabase();
 }

 /**
 * @ User : Android架构
 * @ 创建日期 : 2017/7/13 下午3:24
 * @模块作用 :
 * <p>
 * ====================================================================================================================================
 * ====================================================================================================================================
 */
 private SplashPresenter splashPresenter;

 public ApiModule(SplashAct splashAct) {
 splashPresenter = new SplashPresenter(splashAct, new SplashModel());
 }

 @Provides
 @Singleton
 SplashPresenter provideSplashPresenter() {
 return splashPresenter;
 }

 .....
}

난 단지, 다음 코드를 주입 ​​할 수 사용하는 경우

public class SplashAct extends BaseActivity implements SplashContract.View {

 @Inject
 SplashPresenter presenter;

 @Inject
 Handler handler;

 @Inject
 ApiService apiService;

 @Override
 protected void onCreate() {
 setContentView(R.layout.activity_splash);
 }

 @Override
 protected void initInject() {
 DaggerApiComponent.builder()
 .apiModule(new ApiModule(this))
 .build()
 .inject(this);
 }

 @Override
 protected void initListener() {
 presenter.getWordsInfo(true, apiService);
 }

 @Override
 public void gotoLogInAct() {
 handler.postDelayed(new Runnable() {
 @Override
 public void run() {
 startActivity(new Intent(SplashAct.this, LogInAct.class));
 finish();
 }
 }, 1500);
 }
}

추천

출처blog.51cto.com/14332859/2429542