android--------Dagger2 introduction and simple use (1)

1: What is Dagger2

Dagger is a completely static, compile-time dependency injection framework for Android and Java platforms. It was originally maintained by Square and now throws this bunch of stuff to Google for maintenance.

 

The general IOC framework is implemented by reflection, but Dagger2, as the IOC framework on the Android side, in order not to affect the performance, it is implemented by dynamically generating code through apt.

 

Dagger2 is mainly divided into three modules:

  1. Dependency provider Module, responsible for providing the objects required in dependencies, similar to factory classes in actual coding
  2. Dependency demand-side instance, which declares the dependent object, which corresponds to the business class in actual coding, such as Activity, when you need an object in the Activity, you only need to declare it in it, and the method of declaration will be described below.
  3. The dependency injection component Component is responsible for injecting objects into the dependent demand side. It is an interface in actual coding, and Dagger2 will automatically generate an implementation class for it when compiling.

 

The main workflow of Dagger2 is divided into the following steps:

  1. Pass the dependent demander instance to the Component implementation class
  2. The Component implementation class determines which objects the instance needs to depend on according to the dependency declaration in the instance of the dependent demander
  3. After determining the dependent objects, Component will look for methods to provide these dependent objects in the Module class associated with itself, and if so, set the objects provided in the Module class to the instance of the dependent demander

In layman's terms, it's like you need a piece of clothing now, and it's too troublesome to make it yourself, so you go to the store to buy it. After you explain the type of clothes you want to buy to the store owner, the store owner will look for clothes in your own clothing suppliers. If there is no type you mentioned, we will sell it to you. Among them, you correspond to the above-mentioned dependent demand-side instance, you only need to specify what you need, and the store owner corresponds to the Component implementation class, responsible for meeting the needs of others, and The clothing supplier corresponds to the Module class, which is responsible for the production of clothes. Maybe this is a bit confusing, but after the following Demo, it may be able to help you understand.

 

2: case explanation

Add the apt plugin to the build.gradle file under the project:

  dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

In the build.gradle file of the app directory add:

 provided 'javax.annotation:javax.annotation-api:1.2'
 compile 'com.google.dagger:dagger:2.5'
 apt 'com.google.dagger:dagger-compiler:2.5'

First we create a product class

/***
 * 这是一个商品类
 */
public class CommodityInfo {

    @Inject
    public CommodityInfo (){

    }

    @Override
    public String toString() {
        return "我是商品类对象";
    }
}

We added an @Inject annotation to the constructor, what's the use?

We use ctrl+F9 (mac use Cmd+F9) to compile once, and after the compilation is complete, open the file

 

Auto-generated code:

@Generated(
  value = "dagger.internal.codegen.ComponentProcessor",
  comments = "https://google.github.io/dagger"
)
public enum CommodityInfo_Factory implements Factory<CommodityInfo> {
  INSTANCE;

  @Override
  public CommodityInfo get() {
    return new CommodityInfo();
  }

  public static Factory<CommodityInfo> create() {
    return INSTANCE;
  }
}

 Create a Module class and a Component interface

@Module  //这是一个提供数据的【模块】
public class Demo1Module {

    private Demo1Activity demo1Activity;

    public Demo1Module (Demo1Activity activity){
        this.demo1Activity = activity;
    }

}
//这是一个【组件】/注射器
@Component(modules = Demo1Module.class)
public interface Demo1Component {

    //这个连接器要注入的对象。这个inject标注的意思是,我后面的参数对象里面有标注为@Inject的属性,
    //这个标注的属性是需要这个连接器注入进来的。
    void inject(Demo1Activity demo1Activity);


}

Commodity class objects are now available

public class Demo1Activity extends AppCompatActivity {

    TextView textView;

    @Inject
    CommodityInfo commodityInfo;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo1_layout);
        DaggerDemo1Component.builder()
                //.demo1Module(new Demo1Module(this)) //可要可不要
        .build().inject(this);
        initView();
    }


    private void initView(){
        textView = (TextView) findViewById(R.id.textView);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Demo1Activity.this,"对象值:"+commodityInfo.toString(),Toast.LENGTH_LONG).show();
                textView.setText("对象值:"+commodityInfo.toString());
            }
        });
    }
}

3: Brief introduction

We assume that the Activity in the case represents the home address, and the CommodityInfo represents a certain commodity. Now we need to use the commodity (CommodityInfo) in the home (Activity). We place an order online, and the merchant (representing the CommodityInfo_Factory factory class automatically generated in the case) puts the commodity Factory, can we obtain and use the goods directly at home?

Of course it is impossible. Although the commodity (CommodityInfo) has been produced from the factory (Factory), it has not established a connection with the home (Activity). We also need a new object to deliver the commodity to the door. This heroic character is called— — Courier (Component, Injector).

 That's right, we need such an injector to pass the produced Student object to the container Activity that needs to use the Component, so we need to add the following lines of code to the Activity:

DaggerDemo1Component.builder().demo1Module(new Demo1Module(this)).build().inject(this);

This means that the courier Component has injected the object into this (Activity). Now that the courier has arrived home, we can of course use CommodityInfo directly!

@Inject : 注入,被注解的构造方法会自动编译生成一个Factory工厂类提供该类对象。

@Component: 注入器,类似快递员,作用是将产生的对象注入到需要对象的容器中,供容器使用。

@Module: 模块,类似快递箱子,在Component接口中通过@Component(modules = 
xxxx.class),将容器需要的商品封装起来,统一交给快递员(Component),让快递员统一送到目标容器中。

The effect is as shown in the figure:

 

            

 

 

Code download: https://github.com/DickyQie/android-dagger2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338877&siteId=291194637