Android Dagger2 Component获取某一对象实例

Component常见的方法定义如下所示

@Component
public interface MainActivityComponent {
    public Student getStudent();
}

然后通过DaggerMainActivityComponent.create().inject(this)就可以注入MainActivity的所有被@Inject标识的对象

今天我们介绍Component中的另一种方法定义,可以只注入某个对象

定义如下

@Component
public interface MainActivityComponent {
    Student getStudent();
}

然后在被注入对象中使用方法如下

被注入对象不用@Inject标识,在需要初始化的地方用getStudent()获取

其实严格来说这应该不叫依赖注入,就是单纯的获取一格对象的实例,然后赋值给MainActivity的成员变量

public class MainActivity extends AppCompatActivity {

    Student student;

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

        student = DaggerMainActivityComponent.create().getStudent();
        TextView textView = findViewById(R.id.text);
        textView.setText(student.toString());
    }
}

再看下Dagger为我们生成的DaggerMainActivityComponent中的代码

很简单,主要看getStudent()方法,直接new Student()返回

// Generated by Dagger (https://google.github.io/dagger).
package com.him.hisapp;

public final class DaggerMainActivityComponent implements MainActivityComponent {
  private DaggerMainActivityComponent(Builder builder) {}

  public static Builder builder() {
    return new Builder();
  }

  public static MainActivityComponent create() {
    return new Builder().build();
  }

  @Override
  public Student getStudent() {
    return new Student();
  }

  public static final class Builder {
    private Builder() {}

    public MainActivityComponent build() {
      return new DaggerMainActivityComponent(this);
    }
  }
}

 

 

 

posted @ 2019-06-15 12:18  野猿新一  阅读(24)  评论(0编辑  收藏  举报