In Guice, what's the difference between:
// Inside your AbstractModule subclass:
@Override
public void configure() {
bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
}
And:
@Override
public void configure() {
bind(Service.class).to(ServiceImpl.class);
}
@Provides @Singleton
public ServiceImpl providesService() {
return new ServiceImpl();
}
Are they both the same? When would you use one versus the other? Thanks in advance.
They are nearly identical. The
@Singleton
syntax is useful for annotating@Provides
methods, or annotating the class itself (though I prefer to keep my scoping annotations inside modules).The difference lies in which key is marked Singleton, which has less to do with
@Singleton
versusSingleton.class
(orScopes.SINGLETON
,asEagerSingleton
,@Singleton
class annotations, ortoInstance
implicit singletons) and more to do with what the default syntax makes easy. For example:Above we've bound interface
A
to classAImpl
, and interfaceB
to classBImpl
, but the behavior is different:A
will retrieve the sameAImpl
instance every time.AImpl
will retrieve a differentAImpl
every time, all of which are different thanA
's instance.B
will retrieve the sameBImpl
instance every time.BImpl
will also retrieve that sameBImpl
instance thatB
injects.As you can see, each key is different, and Guice will allow multiple implementation instances if only the interface is bound with Singleton. If you only ever inject
A
andB
interfaces, the behavior looks identical, but if you inject both interfaces and implementations from the same Injector, you may see differing behavior.Similar logic goes for
@Provides
methods:C
will always return the sameCImpl
instance.CImpl
will create a newCImpl
every time, unlessCImpl
has no injectable public zero-arg constructor—then the injection will fail.D
will always return the sameDImpl
instance.DImpl
will return a new instance every time, and each will be different than the one returned byD
.E
will return the sameEImpl
instance every time.EImpl
will also retrieve that same instanceE
injects.This provides some flexibility. Imagine a hypothetical
Cache
that keeps a certain number of most-recently-retrieved objects, where you want to have@User Cache
and@Product Cache
both injectable. If youbind(Cache.class).in(Singleton.class)
, you will have one Cache shared between the objects (and any bareCache
injections), whereas if youbind(Cache.class).annotatedWith(User.class).to(Cache.class).in(Singleton.class)
then the annotated key is kept in singleton scope and each object type will have its own cache.