dagger2s是一个IOC容器框架(即我自己做的事,变成第三方来做)。
添加依赖:dependencies {
  
     implementation 'com.google.dagger:dagger:2.x'
     annotationProcessor 'com.google.dagger:dagger-compiler:2.x'
 }
Module提供对象,Component用于注入对象,Class/Activity使用对象。
源码举例
 编写实体类:
 public class Student {
  
 }
 编写Module类:
 @Module
 public class StudentModule {
  
     @Provides
     public Student providerStudent(){
  
         return new Student();
     }
 }
 编写Component类:
 @Component(modules = {StudentModule.class})
 public interface StudentComponent {
  
     Student providerStudent();
 }
 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());
     }
注意事项:
 一个Model可以注入多个Component中。
 一个Component可以注入多个Activity/Class中。
 一个Activity/Class只能依赖一个Component;如果依赖多个,需要添加dependencies,变相进行依赖传递。
 局部单例:使用@Singleton注解;复杂的依赖传递可以使用自定义的Singleton的别名。
 全局单例:在自定义Application中添加依赖,全局使用。