Android之IOC依赖注入Dagger2

IOC(Inversion of Control)

是一中设计思想,解决业务之间的解耦,是将业务需要的对象交给容器去创建管理(new),而不是传统new获取

场景:Class-A 中用到了 Class-B中的对象b,一般传统情况下,需要A的代码中显示的new对象或者隐身传递参数,才能调用b,那么用IOC依赖注入的方式,可以把Class-B依赖注入到一个Container的容器里面,这样Class-A或者其他Class-X都是可以通过容器获取对象b。

Android之IOC依赖注入Dagger2_第1张图片
IOC模型

在Android有俩个常用的ioc对象框架分别为 Dagger2Hilt

Dagger2

Dagger2 - Github Dagger2是基于Java注解并且在编译期完成的依赖注入,在编译阶段通过APT利用注解处理器来生成java代码

既然是ioc那么就需要:依赖提供方、依赖注入容器(桥梁)、依赖需求放。

Dagger2:

  • @Module 注解提供方
  • @Component 依赖同期
  • @Inject 注解变量对象需求方
  • @dependencies 组合容器,让多个容器组合成一个容器
  • @Provides 构造参数
  • @Singleton 单利模式
  • @Lazy 懒加载需求,先需要通过get()获取对象函数
    implementation 'com.google.dagger:dagger:2.30.1'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.30.1'

@Module

package com.example.dagger2app.object;

import dagger.Module;
import dagger.Provides;

//注册module提供方
@Module
public class HttpObject {


    private String url;

    public HttpObject() {
    }

    public HttpObject(String url) {
        this.url = url;
    }

    
//    @Provides
//    public HttpObject providesHttpObject() {
//        return new HttpObject();
//    }

    //构造Provides 需要返回当前对象, + 传参
    @Provides
    public HttpObject providesHttpObject(String url) {
        return new HttpObject(url);
    }

    //构造参数这里也需要+@Provides
    @Provides
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
package com.example.dagger2app.object;

import dagger.Module;
import dagger.Provides;

@Module
public class DbObject {

    
    private String name = "lss";
    private int age = 20;

    public DbObject() {
    }


    @Provides
    public DbObject providesDbObject() {
        return new DbObject();
    }


    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Component

package com.example.dagger2app;

import com.example.dagger2app.object.DbObject;
import com.example.dagger2app.object.HttpObject;

import dagger.Component;

//容器
@Component(modules = {HttpObject.class, DbObject.class})
public interface MyComponent {

    void injectMainActivity(MainActivity activity);

}

Inject

package com.example.dagger2app;

import android.os.Bundle;
import android.util.Log;

import com.example.dagger2app.object.DbObject;
import com.example.dagger2app.object.HttpObject;

import javax.inject.Inject;

import androidx.appcompat.app.AppCompatActivity;
import dagger.Lazy;


public class MainActivity extends AppCompatActivity {


    private final String TAG = this.getClass().getSimpleName();

    @Inject
    HttpObject httpObject;

    @Inject
    DbObject dbObject;


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


        //方式一注解处理器帮忙new  所以注入的Module构造不能带参数
        DaggerMyComponent.create().injectMainActivity(this);

        //方式二适合构造传参 , 不建议使用,可以通过具体函数方法传参,create的最初目的是new对象
//        DaggerMyComponent.builder()
//                .httpObject(new HttpObject("www.google.com"))
//                .dbObject(new DbObject())
//                .build().injectMainActivity(this);


        Log.e(TAG, "onCreate: " + httpObject.toString());
        Log.e(TAG, "onCreate: " + httpObject.getUrl());


        Log.e(TAG, "onCreate: " + dbObject.toString());
        Log.e(TAG, "onCreate: " + dbObject.getName());
        Log.e(TAG, "onCreate: " + dbObject.getAge());
    }
}

@Singleton 局部单利

​ 关于Singleton 单例,只需要在 ModuleComponent 添加相应的标注


@Module
public class HttpObject {

//省略....

    @Singleton
    @Provides
    public HttpObject providesHttpObject() {
        return new HttpObject();
    }
}



@Singleton
@Component(modules = {HttpObject.class,DbObject.class})
public interface MyComponent {

    void injectMainActivity(MainActivity activity);

}

@Singleton 全局单利

​ 思考?为什么导致?在容器提供注册的时候有上下文活动Activity,导致对象不是同一个

​ 如果是要做全局的单利,那么容器的创建放到 Android - MyApplication 做全局

package com.example.dagger2app;
import android.app.Application;

public class MyApplication extends Application {

    private MyComponent myComponent;

    @Override
    public void onCreate() {
        super.onCreate();
   
        myComponent = DaggerMyComponent.create();
    }

    public MyComponent getMyComponent() {
        return myComponent;
    }
}

@dependencies 组合容器,让多个容器组合成一个容器

​ 副容器的写法修改下,不进行注入上下文,返回当期容器,给主容器使用

Module
package com.example.dagger2app.object;

import dagger.Module;
import dagger.Provides;

@Module
public class FileObject {

    @Provides
    public FileObject providesFileObject(){
        return new FileObject();
    }

}

Component(副,可以有多个)

package com.example.dagger2app;

import com.example.dagger2app.object.FileObject;

import dagger.Component;

@Component(modules = {FileObject.class})
public interface My2Component {

    //使用依赖关系
    FileObject getMy2Component();

}

Component(主,唯一) @dependencies 组合容器

package com.example.dagger2app;

import com.example.dagger2app.object.DbObject;
import com.example.dagger2app.object.HttpObject;

import dagger.Component;

//容器 modules,dependencies 组合容器, 
@Component(modules = {HttpObject.class, DbObject.class}, dependencies = {My2Component.class})
public interface MyComponent {

    void injectMainActivity(MainActivity activity);

}

原理分析

DaggerMyComponent.create().injectMainActivity(this);

通过进入生成的源码查看:

// Generated by Dagger (https://dagger.dev).
package com.example.dagger2app;

import com.example.dagger2app.object.DbObject;
import com.example.dagger2app.object.DbObject_ProvidesDbObjectFactory;
import com.example.dagger2app.object.HttpObject;
import com.example.dagger2app.object.HttpObject_ProvidesHttpObjectFactory;
import dagger.internal.Preconditions;

@SuppressWarnings({
    "unchecked",
    "rawtypes"
})
//方法名:Dagger+容器名ClassName   并且实现了容器接口  
public final class DaggerMyComponent implements MyComponent {
    
  //Module成了新Class的成员变量
    
  private final HttpObject httpObject;

  private final DbObject dbObject;

  private DaggerMyComponent(HttpObject httpObjectParam, DbObject dbObjectParam) {
    this.httpObject = httpObjectParam;
    this.dbObject = dbObjectParam;
  }

    //构建者模式
  public static Builder builder() {
    return new Builder();
  }

    //自动new
  public static MyComponent create() {
    return new Builder().build();
  }

    //依赖注册的活动上下文 ,又重新的生成xxx2的函数工厂
  @Override
  public void injectMainActivity(MainActivity activity) {
    injectMainActivity2(activity);
  }

    /**
    *工厂模式,Provides注册到活动页面,
    *如果在单例模式下面,Lazy<>  get 是双重检验机制
    */
  private MainActivity injectMainActivity2(MainActivity instance) {
    MainActivity_MembersInjector.injectHttpObject(instance, HttpObject_ProvidesHttpObjectFactory.providesHttpObject(httpObject));
    MainActivity_MembersInjector.injectDbObject(instance, DbObject_ProvidesDbObjectFactory.providesDbObject(dbObject));
    return instance;
  }

  public static final class Builder {
    private HttpObject httpObject;

    private DbObject dbObject;

    private Builder() {
    }

    public Builder httpObject(HttpObject httpObject) {
      this.httpObject = Preconditions.checkNotNull(httpObject);
      return this;
    }

    public Builder dbObject(DbObject dbObject) {
      this.dbObject = Preconditions.checkNotNull(dbObject);
      return this;
    }

    public MyComponent build() {
      if (httpObject == null) {
        this.httpObject = new HttpObject();
      }
      if (dbObject == null) {
        this.dbObject = new DbObject();
      }
      return new DaggerMyComponent(httpObject, dbObject);
    }
  }
}

你可能感兴趣的:(Android之IOC依赖注入Dagger2)