我已经阅读了几篇关于 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);
所以我的问题,如上面的代码片段所示:
- 当使用
to(...)
时,我假设使用公共(public)无参数构造函数,并且每次都会返回一个新实例? - 根据上述第 2 条,对于所有
Service.class
请求来说,是否使用相同的impl
实例,还是返回一个新实例? - 与上面的 #3 相同,但现在指定了
Scopes.SINGLETON
。 - 上面的代码可以吗还是我应该使用
bindConstant()
?如果是这样,如何/为什么? - 在什么情况下我应该使用所谓的provider methods ?我有点理解该页面上的示例,但当谈到在我的代码中找到它们的真实用例时,我现在感到窒息。
最佳答案
- 要么使用公共(public)无参构造函数,要么使用@Inject注释的构造函数(推荐)。每次都会返回一个新实例,除非您在 ServiceImpl 上指定范围(通过后面的
bind(ServiceImpl.class).in(...)
行或@Singleton
上的ServiceImpl
注释。 - 在这种情况下,相同的
impl
实例用于Service
的每次注入(inject) - 这是一个编译错误,有充分的理由——你不能在
toInstance
上指定范围。绑定(bind)。 -
bindConstant()
应该用于诸如原始或字符串类型的配置参数之类的事情。欲了解更多信息,请参阅this answer . -
@Provides
方法只是一种更短的书写方式Provider<>
s。如果您不需要它们,请不要使用它们。如果创建对象比简单的构造函数调用更复杂,则通常应该使用它们。
关于java - Guice 绑定(bind) API 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594189/