这是一个场景。假设有一个A类
Class A{
@Inject
public A(){}
}
在我的活动中
public class MainActivity extends Activity{
@Inject
A a;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
在这种情况下如何注入a。
答案 0 :(得分:3)
首先,您需要一个模块:
@Module
class SomeModule{
@SomeScope
@Provides
A proivdeTheAInstance(){
return new A();
}
}
然后您的组件:
@SomeScope
@Component(modules = {A.class}, dependencies={HigherLowerDependencyComponent.class})
interface SomeComponent{
void inject(MainActivity activity);
}
在此之后,在您的活动中,在执行构建后,在onCreate
DaggerSomeComponent.builder().higherLowerDependencnyComponent(implementationHere).build().inject(this)
比你可以@Inject A
但是有一个问题。构造函数注入不能那样工作。为了执行构造函数注入,您的A()
构造函数应至少具有一个依赖项。该构造函数上的@Inject
注释不会调用A()
,而是它的依赖关系(在您的情况下为0),从而使@Inject
构造函数中的A()
不必要。如果您的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;
}
}