Getting started with Android Dagger2 + precautions

dagger2s is an IOC container framework (that is, what I do myself becomes a third party).

添加依赖:dependencies {
    implementation 'com.google.dagger:dagger:2.x'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
}

Module provides objects, Component is used to inject objects, and Class / Activity uses objects.

Source code example
Write entity class:
public class Student {
}
Write Module class:
@Module
public class StudentModule {
    @Provides
    public Student providerStudent () {
        return new Student ();
    }
}
Write component class:
@Component (modules = {StudentModule.class })
public interface StudentComponent {
    Student providerStudent ();
}
Called in Activity:
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "DaggerActivity";

    @Inject
    Student student;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DaggerStudentComponent.create().injectMainActivity(this);
        //        StudentComponent studentComponent = DaggerStudentComponent.builder()
//                .teacherModule(new TeacherModule())
//                .build();
//        teacherComponent.injectMainActivity(this);

        Log.i(TAG, "onCreate: student="+student.hashCode());
    }

Note:
A Model can be injected into multiple Components.
A Component can be injected into multiple Activity / Class.
An Activity / Class can only depend on one Component; if it depends on more than one, it is necessary to add dependencies and pass the dependencies in disguise.
Local singleton: Use @Singleton annotation; complex dependency delivery can use custom Singleton alias.
Global singleton: add dependency in custom Application for global use.


 

Published 31 original articles · Like1 · Visits1159

Guess you like

Origin blog.csdn.net/quietbxj/article/details/105388003