Reputation: 56914
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".
// 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?impl
instance used for ever Service.class
request, or is a new one returned?Scopes.SINGLETON
specified.bindConstant()
? If so, how/why?Upvotes: 1
Views: 486
Reputation: 12922
bind(ServiceImpl.class).in(...)
line or an @Singleton
annotation on ServiceImpl
.impl
instance is used for every injection of Service
toInstance
binding.bindConstant()
should be used for things like configuration parameters that are primitive or String types. For more information, see this answer.@Provides
methods are simply a shorter way of writing Provider<>
s. 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.Upvotes: 1