例如:
class A{
B b;
C c;
@Inject
A(B b){
this.b = b;
}
@Inject
A(C c){
this.c = c;
}
}
在其中一个模块中:
@Module
public class BModule {
private final B b;
public BModule(B b){
this.b = b;
}
@Provides
BInterface provideB(){
return b;
}
}
但是我收到错误,无法在类中注入(inject)两个构造函数,我应该怎么处理这个问题?谢谢!
最佳答案
类只被构造一次;两个构造函数永远不会在同一个实例上同时调用,因此有两个带有 @Inject 注释的构造函数意味着 Dagger 必须选择一个。 你想用这两个带注释的构造函数来完成什么行为?
理想情况下,结合构造函数。
@Inject
A(B b, C c){
this.b = b;
this.c = c;
}
或者将其中之一切换为method injection如果绝对必要:
@Inject
A(B b){
this.b = b;
}
@Inject
void initialize(C c){ // Dagger calls this automatically
this.c = c;
}
关于android - Dagger如何注入(inject)多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539356/