Android 匕首2未注入从属模块
我检查了所有的问题,但没有发现任何线索。我将问题简化为一个最简单的代码: 情况: 我想要:Android 匕首2未注入从属模块,android,module,null,inject,dagger-2,Android,Module,Null,Inject,Dagger 2,我检查了所有的问题,但没有发现任何线索。我将问题简化为一个最简单的代码: 情况: 我想要: CatComponent catComponent = DaggerCatComponent.builder() .kameModule(new KameModule(MainActivity.this)) .build(); catComponent.getCatAnalyzer().analyze(); 我创建了一个组件: @Component(modu
CatComponent catComponent = DaggerCatComponent.builder()
.kameModule(new KameModule(MainActivity.this))
.build();
catComponent.getCatAnalyzer().analyze();
我创建了一个组件:
@Component(modules = {KameModule.class, CatAnalyzerModule.class})
public interface CatComponent {
CatAnalyzer getCatAnalyzer();
}
和模块:
@Module
public class KameModule {
private Context context;
public KameModule(Context context) {
this.context = context;
}
@Provides
KameCat provideKameCat() {
return new KameCat(context );
}
}
@Module(includes = KameModule.class)
public class CatAnalyzerModule {
@Inject
KameCat cat;
@Provides
CatAnalyzer provideCatAnalyzer() {
return new CatAnalyzer(cat);
}
}
课程及类别:
public class KameCat {
Context context;
public KameCat(Context context) {
this.context = context;
}
public void doCatStuff() {
Toast.makeText(context, "Poo and Meow", Toast.LENGTH_LONG).show();
}
}
public class CatAnalyzer {
@Inject
KameCat cat;
@Inject
public CatAnalyzer(KameCat cat) {
this.cat = cat;
}
void analyze() {
cat.doCatStuff();
}
}
当我从CatComponent检索CatAnalyzer对象时,它的cat
字段为空。
我不知道为什么匕首不会注射。你能给我一些指导吗?正确的代码:
@Module(includes = KameModule.class)
public class CatAnalyzerModule {
@Inject //remove this
KameCat cat;// remove this
@Provides
// Add cat as a argument and let KameModule provide it..
CatAnalyzer provideCatAnalyzer(KameCat cat) {
return new CatAnalyzer(cat);
}
}
感谢:
上的
@Inject
注释是多余的,因为类是在CatAnalyzerModule
中提供的。您可以删除模块,或者构造函数上的@Inject
注释。无论哪种方式,KameCat
上的@Inject
注释都是多余的。此外,对于更惯用的依赖注入,KameModule
将@提供上下文,以便它可以在任何模块中的任何位置参与。然后,provideKameCat
方法也可以将上下文
作为参数,类似于您使用providedatanalyzer(KameCat)
所做的操作。最后,如果您最终在@Component.modules
列表中同时包含两个模块,则不需要使用@Module.includes
。