Guice:当我在构造函数上有过多的 @Inject 时会发生什么
我有一个类 SomeClass
和一个 SomeModule
来向 Guice 注册它。
我发现构造函数 SomeClass
仅由 SomeModule
调用,并且 SomeModule
是唯一绑定 SomeClass
的地方代码> 发生。
这意味着 SomeClass
的构造函数上的 @Inject
是不需要的,因为 prop1
和 prop2
被注入到 < code>SomeModule 并传递给构造函数。测试似乎也证明了我的发现。
我的问题是,当 Guice 看到这样的 @Inject
时会做什么?
另外如果我的@Inject
过多会有什么副作用?
public static class SomeModule extends PrivateModule {
@Provides
@Singleton
@Exposed
private SomeClass someClass( SomeObject prop1, String prop2) {
return new SomeClass(prop1, prop2);
}
}
public class SomeClass {
@Inject // unnecessary
public SomeClass(SomeObject prop1, String prop2){
...
}
}
如果我的理解是正确的,当你想将 Guice 管理的对象注入到构造函数的参数中时,你可以使用 @Inject
构造函数。
例如,如果我有 bind(SomeClass.class).in(Singleton.class)
以及 prop1
和 prop2
的绑定,则 < code>@Inject SomeClass
构造函数,以便将 prop1
和 prop2
注入到构造函数中。
但由于情况并非如此,这使得这里的 @Inject
不必要了
干杯
I have a class SomeClass
and a SomeModule
to register it with Guice.
I found out that the constructor SomeClass
is only called by SomeModule
, and that SomeModule
is the only place where binding for SomeClass
happens.
This means that the @Inject
on SomeClass
's constructor is not needed since prop1
and prop2
are injected inside SomeModule
and passed to the constructor. And the testing also seems to prove my findings.
My question is that what Guice will do when it sees a @Inject
like this?
Also what side effect will there be if I have an excessive @Inject
?
public static class SomeModule extends PrivateModule {
@Provides
@Singleton
@Exposed
private SomeClass someClass( SomeObject prop1, String prop2) {
return new SomeClass(prop1, prop2);
}
}
public class SomeClass {
@Inject // unnecessary
public SomeClass(SomeObject prop1, String prop2){
...
}
}
If my understanding is correct, you @Inject
a constructor when you want to inject objects managed by Guice into the parameters of the constructor.
e.g. if I have bind(SomeClass.class).in(Singleton.class)
and bindings for prop1
and prop2
, it makes sense to @Inject
SomeClass
constructor in order to inject prop1
and prop2
into the constructor.
But since this isn't the case, this makes the @Inject
here unnecessary
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
引用@Deepak的评论作为答案:
Quoting @Deepak's comment as the answer: