我检查了所有问题,但没有发现任何线索。我把问题解决了最简单的代码:
情况: 我希望:
@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();
}
}
课程:
cat
当我从CatComponent检索我的CatAnalyzer对象时,它有defaultTasks = ['test']
字段为空。
我不知道为什么Dagger不会注射它。你能以某种方式指导我吗?
答案 0 :(得分:2)
正确的代码:
@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);
}
}
感谢: https://www.future-processing.pl/blog/dependency-injection-with-dagger-2/