can you get 2 singleton instances of the same underlying type?
this is obviously trivial in spring as it is based on named instances to which you attach a scope but I can't see the equivalent in guice which is about binding types to implementation classes. Note that I don't want to have to bind to the instance as the instances in question are injected with other dependencies by guice.
Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design. It might happen in some cases, e.g.: Non thread safe singleton with lazy initialization: several threads are trying to get an instance and creates multiple instances.
In software engineering, the multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a map.
@Singleton - Single instance for lifetime of the application.
Guice Basic Bindings. Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class. This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.
It's easy in Guice too! Create two biding annotations, say @One
and @Two
and then
bind(MySingleton.class).annotatedWith(One.class).toInstance(new MySingleton());
bind(MySingleton.class).annotatedWith(Two.class).toInstance(new MySingleton());
and then
@Inject
public SomethingThatDependsOnSingletons(@One MySingleton s1,
@Two MySingleton t2) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With