[英]Why am I getting null instead of the @Inject-ed field?
在下面的代码中,我希望获得一个新的Soap
对象( #07
行),但我得到了null
。 我在这里想念什么?
01| public class ExampleUnitTest {
02| @Test
03| public void DaggerTest() throws Exception {
04| MyComponent myComponent = DaggerMyComponent.create();
05| IThing thing = myComponent.getThing();
06| Impl impl = thing.getImpl();
07| ISoap soap = impl.soap;
08| Assert.assertNotNull(soap); // fails here: soap is null!
09| }
10| }
11|
12| interface ISoap{}
13| class Soap implements ISoap{}
14|
15| class Impl{
16| @Inject public ISoap soap;
17| }
18|
19| @Module
20| class MyModule {
21| @Provides IThing getThing(){ return new Thing(); }
22| @Provides ISoap getSoap() { return new Soap(); }
23| }
24|
25| @Component(modules = MyModule.class)
26| interface MyComponent {
27| IThing getThing();
28| ISoap getSoap();
29| }
30|
31| interface IThing{
32| Impl getImpl();
33| }
34|
35| class Thing implements IThing{
36| @Override public Impl getImpl() { return new Impl(); }
37| }
要使用匕首字段注入(使用@Inject
注释字段),您需要在创建对象后手动注入对象。
class Impl {
@Inject public ISoap soap; // requires field injection
}
// will only work with something like this
Impl myImpl new Impl();
component.inject(myImpl); // inject fields
这不是你在做什么。 您正在自己的模块中创建对象,并期望对其进行初始化。 您创建的对象和你没有初始化。
如果使用模块,则需要返回初始化的对象。
// to create your thing, you need a soap. REQUIRE it in your parameters,
// then create your _initialized_ object (you could also use a setter)
@Provides IThing getThing(ISoap soap) { return new Thing(soap); }
那你可以用
IThing thing = myComponent.getThing();
会有肥皂
另外我也不知道您要通过从吸气剂返回一个新对象来尝试做什么。
class Thing implements IThing{
@Override public Impl getImpl() { return new Impl(); }
}
如果你调用new
自己,同样,你正在试图做的匕首工作。
您应该对构造函数注入有所了解。 然后,您可以整体上删除该模块,而不会在示例中添加任何功能。
有很多很好而详尽的教程,例如,我的有关Dagger基础知识的博客文章应该对Dagger进行很好的介绍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.