Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple guice singletons of the same type

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.

like image 431
Matt Avatar asked Aug 03 '09 11:08

Matt


People also ask

Can you have multiple singletons?

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.

How many instances can singleton have?

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.

What is singleton in Guice?

@Singleton - Single instance for lifetime of the application.

What does bind do in Guice?

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.


1 Answers

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) { ... }
like image 152
Marcin Avatar answered Nov 15 '22 17:11

Marcin