IAmYourFaja
IAmYourFaja

Reputation: 56914

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".

// 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:

  1. When using to(...), I assume the public no-arg ctor is used, and a new instance is returned every time?
  2. Per #2 above, is the same impl instance used for ever Service.class request, or is a new one returned?
  3. Same as #3 above, but now with Scopes.SINGLETON specified.
  4. Is the above code OK or should I be using bindConstant()? If so, how/why?
  5. Under what circumstances should I be using so-called provider methods? I sort of understand the example on that page, but am now choking when it comes to finding a real-world use case for them in my code.

Upvotes: 1

Views: 486

Answers (1)

Tavian Barnes
Tavian Barnes

Reputation: 12922

  1. Either the public no-argument constructor is used, or an @Inject-annotated constructor (that would be recommended). A new instance is returned every time, unless you specify a scope on ServiceImpl (either by a later bind(ServiceImpl.class).in(...) line or an @Singleton annotation on ServiceImpl.
  2. In this case, the same impl instance is used for every injection of Service
  3. That is a compile error, for good reason -- you can't specify a scope on a toInstance binding.
  4. bindConstant() should be used for things like configuration parameters that are primitive or String types. For more information, see this answer.
  5. @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

Related Questions