[英]How can I construct a class when the super class uses @Inject?
I have the following code: 我有以下代码:
public abstract class AbstractClass<T> {
final A a;
@Inject
AbstractClass(A a) {
this.a = a;
}
}
public class B extends AbstractClass<C> {
final D d;
@Inject
B(D d) {
super(); // this fails
this.d = d;
}
}
My class B
extends AbstractClass
and AbstractClass
uses @Inject
to inject A
into it. 我的
class B
扩展了AbstractClass
而AbstractClass
使用@Inject
将A
注入其中。 In class B
I cannot call super()
because AbstractClass
has an argument in the constructor. 在类
B
我无法调用super()
因为AbstractClass
在构造函数中有一个参数。 How can I handle the dependency injection of the superclass in the subclass to get super()
working? 如何处理子类
super()
类的依赖项注入以使super()
工作?
How can I construct a class when the superclass uses @Inject
? 当超类使用
@Inject
时,我该如何构造一个类?
You need to accept an A
as well: 您还需要接受一个
A
:
@Inject
B(A a, D d) {
super(a);
this.d = d;
}
Then Guice should inject both the A
and the D
, and you just pass the A
up to the superclass constructor. 然后,Guice应该同时注入
A
和D
,然后将A
传递给超类构造函数。 Just because a constructor is marked with @Inject
doesn't mean it can only be invoked by Guice... In fact, I would actually remove the @Inject
from AbstractClass
- unless Guice has some magic I'm unaware of, it's not going to be able to inject that anyway. 仅仅因为构造函数被
@Inject
标记并不意味着它只能被Guice调用...实际上,我实际上会从AbstractClass
删除@ @Inject
除非Guice有我不知道的魔术,否则它不会无论如何都可以注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.