Dagger2 如何执行默认构造函数的构造函数注入

Dagger2 how to perform constructor injection of a default constructor

这是一个场景。假设有一个 class A

Class A{

@Inject
public A(){}

}

在我的 Activity

 public class MainActivity extends Activity{

    @Inject
    A a;

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    }
}

如何在这种情况下注入 a。

好的,首先你需要一个模块:

@Module
class SomeModule{
  @SomeScope
  @Provides
  A proivdeTheAInstance(){
   return new A();
  }
}

然后你的组件:

@SomeScope
@Component(modules = {A.class}, dependencies={HigherLowerDependencyComponent.class})
interface SomeComponent{
 void inject(MainActivity activity);
}

在你的 activity 之后,在你执行构建之后,在 onCreate

DaggerSomeComponent.builder().higherLowerDependencnyComponent(implementationHere).build().inject(this)

你做不到@Inject A

但是有一个问题。构造函数注入不是那样工作的。为了执行构造函数注入,您的 A() 构造函数应该至少有一个依赖项。该构造函数上的 @Inject 注释不会调用 A() 但它的依赖项,在您的情况下为 0,因此 A() 构造函数中的 @Inject 是不必要的。如果您的 A 构造函数是这样的,您的问题就会成立:

    @Inject
    public A(SomeDependency dependency){
     this.someDependency = dependency;
    }

SomeDependency 也将在模块中提供:

@Module
class SomeModule{
  @SomeScope
  @Provides
  A proivdeTheAInstance(SomeDependency someDependency){ //now dagger will look to find this one
   return new A();
  }

@SomeScope
  @Provides
  SomeDependency proivdeSomeDependencyInstance(){ //which is provided here 
   return new SomeDependency();
  }
}

你可以像往常一样继续:

class A{
private SomeDependency someDependency;
 @Inject
 public A(SomeDependency someDependency){ //the inject will require the SomeDependency
  this.someDependency = someDependency;
  }
}

编辑: 如果 dagger 已经知道如何提供实例,则不需要模块,您可以在 class A() 的构造函数上方执行 @Inject:

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