Guice:当我在构造函数上使用过多的 @Inject 时会发生什么
Guice: what happens when I have excessive @Inject on a constructor
我有一个 class SomeClass
和一个 SomeModule
来向 Guice 注册它。
我发现构造函数 SomeClass
仅由 SomeModule
调用,并且 SomeModule
是唯一发生绑定 SomeClass
的地方。
这意味着 SomeClass
的构造函数中的 @Inject
是不需要的,因为 prop1
和 prop2
被注入到 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
的绑定,那么 @Inject
SomeClass
构造函数就可以注入 prop1
和 prop2
进入构造函数。
但由于情况并非如此,因此这里的 @Inject
变得不必要
干杯
引用@Deepak 的评论作为答案:
You need @Inject if you were defining a binding in the configure method instead of creating a Provider for this class. When you define a binding in the configure method, you are telling Guice to instantiate the object for you. That is when it looks for a constructor with @Inject to figure out what dependencies it has to Inject to construct that object. In case of Provider, you are creating the object yourself by passing all the dependencies required for that class as arguments. So, @Inject has no meaning at that case
我有一个 class SomeClass
和一个 SomeModule
来向 Guice 注册它。
我发现构造函数 SomeClass
仅由 SomeModule
调用,并且 SomeModule
是唯一发生绑定 SomeClass
的地方。
这意味着 SomeClass
的构造函数中的 @Inject
是不需要的,因为 prop1
和 prop2
被注入到 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
的绑定,那么 @Inject
SomeClass
构造函数就可以注入 prop1
和 prop2
进入构造函数。
但由于情况并非如此,因此这里的 @Inject
变得不必要
干杯
引用@Deepak 的评论作为答案:
You need @Inject if you were defining a binding in the configure method instead of creating a Provider for this class. When you define a binding in the configure method, you are telling Guice to instantiate the object for you. That is when it looks for a constructor with @Inject to figure out what dependencies it has to Inject to construct that object. In case of Provider, you are creating the object yourself by passing all the dependencies required for that class as arguments. So, @Inject has no meaning at that case