使用 Dagger 时,哪些方法允许在也通过注入实例化的对象上自由/轻松地实例化 @Inject 字段。
例如,下面的代码会将 Bar 类型的对象注入给定的 Foo 对象。它将以显示的两种方式之一执行此操作。但是,每个 Bar 对象的 Sly 字段与该行为不匹配。
富
public class Foo {
@Inject Bar bar;
public String getValue() {
return "Foo's bar value: " + bar.getValue();
}
}
砰
public class Bar {
@Inject Sly sly;
public String getValue() {
return "Bar's sly value: " + sly.getValue();
}
}
狡猾
public class Sly {
public String getValue() {
return "Hey!";
}
}
模块
@Module(
injects = {
Foo.class,
Bar.class
}
)
public class ExampleTestModule {
@Provides
Bar provideBar() {
return new Bar();
}
@Provides
Sly provideSly() {
return new Sly();
}
}
测试
public void testWorksWithInject() {
Foo foo = new Foo();
ObjectGraph.create(new ExampleTestModule()).inject(foo);
assertEquals("...", foo.getValue()); // NullPointerException
}
public void testWorksWithGet() {
Foo foo = ObjectGraph.create(new ExampleTestModule()).get(Foo.class);
assertEquals("...", foo.getValue()); // NullPointerException
}
在任何一种情况下,Bar 的 Sly 都没有被实例化/@Injected。当然,Dagger 允许构造函数注入,从而解决了这个问题。我想知道是否有其他方法可以将这些类放入构造函数的参数列表中。什么适合你?