Dagger2 explore 1-- four basic components in mind (a)

       The reason many people self-study, I contacted Dagger 2 framework is just joined the company when the teacher to arrange learning tasks, learning is the group training.

       Heard the news, I thought it was the people's department turns to me lecture.

       Later mentors told me that the group training mean, I'll take myself to learn this framework, then everyone in the group to put forward training.

       

       No way, read a lot of online-related blog, wasting a lot of time, finally learning anything, what I also recorded recent progress learning.

       What history do not speak, you can see this blog I wanted to history what science you have been stuffed spit, or the code line and learn faster.

A configuration environment

       Add code in build.gradle module in:

dependencies {
    ......
    //dagger2
    implementation 'com.google.dagger:dagger:2.7'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.7'
    //butterknife
    implementation 'com.jakewharton:butterknife:10.0.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'
}

      In order to write a simple code behind the ButterKnife arranged together.

      Add the following code in Project build.gradle (This code is used to configure ButterKnife, configuration might not reported TimeOut error):

allprojects {
    repositories {
        google()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
        jcenter()
    }
}

      Here configuration is complete, ButterKnife can save a lot of code for us, because ButterKnife and D Agger manufacturers is the same, but also common in many places, not much to explain the principles, brought on by.

Two source code analysis

     Let's create a simple Tools category:

public class Tools {
    @Inject
    public Tools(){}
}

       Does not require any property, just mark an empty constructor method @Inject, then we use the Ctrl + F9 to compile.

       Dagger2 is formulated by tag to write code, reduce labor we repeat writing code.

       Here mentioned a word "formulaic", is actually very good understanding.

       For example, you give you give your favorite girl tell the truth, you should talk to the bedroom brothers rehearse a hundred times confession process. The woman downstairs to sleep, you clear a clear voice, someone to lay your lights, you finish called the girl's name, someone flying behind a pink balloon love, you just said three words that shame shame, surrounded on all cry, "he promised, promised him ......"

       The girl was touched, and then deny you ......

       Keke, talk way off!

       In short, formulaic stuff like this, a good flow fixed, you just want to make a special gesture, others will know how to do. why? Because the processes are formulaic, fixed, ran thousands of times already, and we can knock out eyes closed. So also in the program do not re-create the wheel. You just want to make a mark, like @Inject mentioned above, the rest of the tedious tasks to the computer like duplication of effort.

       Well, see @Inject this mark, the computer has done anything at all?

       After compilation will find the build in more than one file (you ask me which path I take you back to find, listen to me, slowly?!), Called Tools_Factory class, as follows:

public enum Tools_Factory implements Factory<Tools> {
  INSTANCE;

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

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

        This is the AS automatically generated code. A factory class, the class its name, is a plant. Methods are created using the create (), get new Tools object through the get () method.

        I posted the following four basic components of the code, and take up the first frame:

        First MainActicity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);//ButterKnife绑定Activity

    }

    @OnClick({R.id.turn_firstactivity})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.turn_firstactivity:
                startActivity(new Intent(this, FirstActivity.class));
                break;
        }
    }
}

        It is simply a jump, jump to FirstActivity we are going to use.

        Activity_main posted about this layout, I usually hate people do not see the blog posted the code finished, I certainly would not have made this mistake.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/turn_firstactivity"
        android:text="四大基本组件"/>
</LinearLayout>

        Next is FirstActivity, the main Activity that is our first example of a public class FirstActivity the extends AppCompatActivity 

    @BindView(R.id.fist_text_1)    TextView text1;
    @BindView(R.id.fist_text_2)    TextView text2;

    @Inject    Tools tool1;
    @Inject    Tools tool2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        ButterKnife.bind(this);//绑定View和Activity
} }

        Code is well understood, with ButterKnife to bind directly View and Activity, save a lot of code, and the code is saving the aforementioned reflect the "formulaic" in.

        And the corresponding layout code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/fist_text_1"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/fist_text_2"
        />

</LinearLayout>

         We then create interfaces FirstComponent:

@Component
public interface FirstComponent {

    void inject(FirstActivity activity);

}

       This method name inject free to rewrite, but in order to facilitate the later people to read, I suggest you follow common rules to write, so that later take over your code few people call you a few words.

       At this point, we need to Ctrl + F9 to compile a little longer. Because there is a need Dagger2 file is automatically generated after that we can use.

       Next, add the code in FirstActivity in:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        ButterKnife.bind(this);

        DaggerFirstComponent.builder()
                .build()
                .inject(this);
        text1.setText(tool1.toString());
        text2.setText(tool2.toString());
    }

        The number of documents that DaggerFirstComponent.java, you can Ctrl + left mouse button click DaggerFirstComponent jump to the file view.

        You can not find the file in front of the automatically generated which can then click the same icon as sight, automatically navigate to the corresponding folder.

        The file name is a combination of Dagger + Component out, and indeed inherited the Component interface methods which were rewritten.

        DaggerFirstComponent code is as follows:

public final class DaggerFirstComponent implements FirstComponent {
  private MembersInjector<FirstActivity> firstActivityMembersInjector;

  private DaggerFirstComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

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

  public static FirstComponent create() {
    return builder().build();
  }

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {

    this.firstActivityMembersInjector =
        FirstActivity_MembersInjector.create(Tools_Factory.create());
  }

  @Override
  public void inject(FirstActivity activity) {
    firstActivityMembersInjector.injectMembers(activity);
  }

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

    public FirstComponent build() {
      return new DaggerFirstComponent(this);
    }
  }
}

         Obviously Builder Builder mode.

         Then the other hand calls for DaggerFirstComponent's Activity

        DaggerFirstComponent.builder()
                .build()
                .inject(this);

         First Builder inside initialize a class, the class then calls Builder build () method of DaggerFirstComponent constructed.

         DaggerFirstComponent constructor, there initialize the initialization function to DaggerFirstComponent held an internal member firstActivityMembersInjector assignment.

         Note that this line of code:

    this.firstActivityMembersInjector = FirstActivity_MembersInjector.create(Tools_Factory.create());

         This also involves a critical file, remember suffix MembersInjector on the line.

         Some small partners might want to ask, why I do not put all the one-time auto-generated files are listed?

         According to the logic step by step, this is better understood.

         This is also the last one: a factory class Factory, an interface implementation class DaggerComponent, plus assembled class MemberInjector (if you see a fourth, possibly ButterKnife generated, are interested can look)

         Why should MemberInject called the assembled class, listen to me speak slowly come.

         MemberInject.java source code is too long, just look at first create ()

  private final Provider<Tools> tool1AndTool2Provider;

  public FirstActivity_MembersInjector(Provider<Tools> tool1AndTool2Provider) {
    assert tool1AndTool2Provider != null;
    this.tool1AndTool2Provider = tool1AndTool2Provider;
  }

  public static MembersInjector<FirstActivity> create(Provider<Tools> tool1AndTool2Provider) {
    return new FirstActivity_MembersInjector(tool1AndTool2Provider);
  }

        Probably means that first passed in a factory class Factory.create (), Recall factory class on two methods: create () and get (). Then create a good factory class assigned MemberInject class member variable is probably better to build the factory class, save for future use.

       Here we have to build () finished the race. Stroked a stroke now did what, DaggerFirstComponent this class called Factory.create (), and then gave it to MemberInject, save yourself an example of a MemberInject. To this step, in fact, was a return to the Component, Component and then continue in existing methods only.

       Attention to this point, here is a return to the Component! Draw the focus back to the exam.

       If you look carefully enough method code may notice, DaggerFirstComponent There is a create (), is the corresponding builder (). Build (). Dependency injection means can be simplified into the following code in this form:

        DaggerFirstComponent.create().inject(this);

        Yes, indeed so, but it is strongly not recommended to write. Draw focus strongly not recommended!

        Because they do not comply with the principle of opening and closing, the reasons will be mentioned later.

        DaggerFirstComponent class inherits FirstComponent interface rewrite inject method:

  @Override
  public void inject(FirstActivity activity) {
    firstActivityMembersInjector.injectMembers(activity);
  }

       Inject can see examples of methods just to pass a MemberInject Activity.

       MemberInject are fed what things?

       Factory class create better get into, Activity also gave it.

       Why call it assembled class! Look at the code:

    instance.tool1 = tool1Provider.get();

       Activity is an example instance, depending statement found by prior injection Activity Tools example, in a factory and then a new instance of the class object tool1Provider get () assigned to it.

       DaggerFirstComponent things are ready for it, he is only responsible for assembly.

       Here, the entire dependency injection completed.

       Results are as follows:

       

      Injection of two different Tools.

      Recall, in fact, the logic is very simple.

       1, to be injected in the Activity-dependent, the injected labeled with @Inject instance of the class dependent tools

       2, the die injecting the required class constructor Tools Tools @Inject indicia on (), the compiler generates Factory factory classes based on this

       3, on the interface FirstComponent @Component mark, and the writing method Inject

       4, the compiler generates DaggerFirstComponent.java

       5, call DaggerFirstComponent method instantiates instances of plant and Activity class are to MemberInjecter

       6, MemberInjecter assembled, dependency successfully injected.

 

       And so on, how they talk about the four basic components of the two?

       Because the two has been able to substantially complete a simple dependency injection, and then speak the next chapter to a further method of factory class.

Guess you like

Origin www.cnblogs.com/yuanxixing/p/11525027.html