[英]Guice Binding API by Example
I have read several articles and tutorials on Guice (3.0), and now have a few lingering questions before I can "tie it all together". 我已经阅读了有关Guice(3.0)的几篇文章和教程,现在有一些挥之不去的问题,然后才能将它们“捆绑在一起”。
// 1. Binds via public, no-arg "ServiceImpl()" ctor?
bind(Service.class).to(ServiceImpl.class);
// 2. Every client-side request for a Service instance returns the same
// ServiceImpl instance?
ServiceImpl impl = new ServiceImpl(...);
bind(Service.class).toInstance(impl);
// 3. Every client-side request for a Service instance returns the same
// SINGLETON ServiceImpl instance?
ServiceImpl impl = new ServiceImpl(...);
bind(Service.class).in(Scopes.SINGLETON).toInstance(impl);
// 4. Should this be a call too bindConstant() instead of toInstance()
// instead? If so, how/why?
Integer timeout = 1000 * 60; // 60 seconds
bind(Integer.class).named(Names.named("TIMEOUT")).toInstance(timeout);
So my questions, as implied by the code snippet above: 所以我的问题,如上面的代码片段所示:
to(...)
, I assume the public no-arg ctor is used, and a new instance is returned every time? 当使用to(...)
,我假设使用了公共的无参数ctor,并且每次都会返回一个新实例? impl
instance used for ever Service.class
request, or is a new one returned? 对于以上#2,是否曾经对Service.class
请求使用相同的impl
实例,还是返回了一个新实例? Scopes.SINGLETON
specified. 与上面的#3相同,但现在指定了Scopes.SINGLETON
。 bindConstant()
? 上面的代码可以吗,还是应该使用bindConstant()
? If so, how/why? 如果是这样,如何/为什么? Thanks in advance! 提前致谢!
bind(ServiceImpl.class).in(...)
line or an @Singleton
annotation on ServiceImpl
. 每次都返回一个新实例,除非您在ServiceImpl上指定范围(通过稍后的bind(ServiceImpl.class).in(...)
行或ServiceImpl
上的@Singleton
批注指定)。 impl
instance is used for every injection of Service
在这种情况下,每次Service
注入都使用相同的impl
实例 toInstance
binding. 这是一个编译错误,这有充分的理由-您无法在toInstance
绑定上指定范围。 bindConstant()
should be used for things like configuration parameters that are primitive or String types. bindConstant()
应该用于诸如原始或String类型的配置参数之类的东西。 For more information, see this answer . 有关更多信息,请参见此答案 。 @Provides
methods are simply a shorter way of writing Provider<>
s. @Provides
方法只是编写Provider<>
的一种较短方法。 If you don't have a need for them, don't use them. 如果您不需要它们,请不要使用它们。 They should generally be used if creating an object is more complicated than a simple constructor call. 如果创建对象比简单的构造函数调用更复杂,通常应使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.