I want to access multiple instances singletonA and singletonB of a no-interface Singleton MySingleton. The instances are first defined in another Singleton Configurator class:
MySingleton.java
@Singleton
@LocalBean
public class MySingleton {
...
}
Configurator.java
@Singleton
@Startup
@LocalBean
public class Configurator {
@EJB MySingleton singletonA;
@EJB MySingleton singletonB;
}
The code above, appearently works.
Now, I need to inject these 2 instances of MySingleton in a Message-Driven Bean:
MDB.class
@Stateless
public class MDB implements MessageListener {
@EJB (lookup="?") MySingleton singletonA;
@EJB (mappedName="??") MySingleton singletonB;
}
But at this point I am completely lost. I know that I could make things simpler by defining the 2 instances as 2 (empty) implementations of a unique interface. But I have some problems because the class contains some non static fields, so I can’t define it as an Interface.
EDIT
Because of the nature of MDB, I can’t pass the Singletons by reference.
Finally, I would like to avoid creating two identical implementations of MySingleton.
Thanks to the answers received I have been rethinking at the whole architecture and I must agree on the fact that having MySingleton defined as Stateful would be fine as well.
First of all, in Configurator MySingleton singletonA and MySingleton singletonB are same. That is because whole point of @Singleton is to have only one instance, no matter how many times and where it is injected (in same JVM). Container creates instance before you inject it first time and after that same instance will be shared. So you can as well go and inject (rather only once) it again in AnotherEJB.
Even if we assume case without Singleton (Staless for example), using @EJB for injection does not produce new entries available for injection in somewhere else. So if you inject something via @EJB in class A, you cannot via injection pass reference to class B. To pass reference, method call is good way.