Java Guice:注入用于实现抽象方法的参数
以下是我遇到的问题的一个例子:Java Guice:注入用于实现抽象方法的参数,java,dependency-injection,abstract-class,guice,Java,Dependency Injection,Abstract Class,Guice,以下是我遇到的问题的一个例子: public interface IFoo { ... } public abstract class Helper implements IFoo { public Helper() { ... } protected abstract X helperMethod(); } public class Foo extends Helper { private final String aaa; @Inject public F
public interface IFoo { ... }
public abstract class Helper implements IFoo {
public Helper() { ... }
protected abstract X helperMethod();
}
public class Foo extends Helper {
private final String aaa;
@Inject
public Foo(String aaa) { this.aaa = aaa; }
@Override
X helperMethod() { doSomethingUsingWhatsInjected(aaa); }
}
问题是当我像这样将IFoo绑定到Foo时:
bind(IFoo.class).to(Foo.class).in(Singleton.class);
似乎在注入aaa
之前调用了helperMethod()
,因为我将aaa
视为null
。但是,如果我不使用类Helper
并直接在Foo
中内联它的所有代码,guice就不会挣扎
这两种方法有什么区别?为什么在我们知道从哪里得到
IFoo
的实现之前调用了helperMethod()
?我们可以将Helper
与注入一起使用吗?您确定不是从Helper
的构造函数中调用helperMethod
?您在发布的代码中忽略了该部分,但它将与您看到的行为相匹配
public class Test {
interface IFoo { }
static abstract class Helper implements IFoo {
Helper() { helperMethod(); }
abstract void helperMethod();
}
static class Foo extends Helper {
private final String aaa;
Foo(String aaa) { this.aaa = aaa; }
@Override
void helperMethod() { System.out.println(String.valueOf(aaa)); }
}
public static void main(String[] args) {
// Call helperMethod twice:
// once in the Helper.Helper(), once right here.
new Foo("expected").helperMethod();
// output:
// null
// expected
}
}
Foo做的第一件事是隐式调用其超类构造函数,就像键入了super()
;这必然发生在子类构造函数的第一条语句中。因此,这甚至在设置像aaa
这样的最终变量之前就发生了,因此在Foo中被重写的方法将aaa
视为null。在我的示例中,这不是特定于Guice的,但是Guice注入可以像其他任何东西一样触发构造函数
对这个问题进行了更深入的讨论。你完全正确。我选中了,正在从
Helper
的构造函数中调用helperMethod()。我在写示例时错误地忽略了这个细节。这回答了我的问题,谢谢!