I'm trying to find a way to choose between several EJBs to inject at runtime.
The scenario goes like this: There are i.e. 2 beans (ejbA, ejbB) which all implement the same interface (ejbInterface). At several injection points (other managed beans, i.e. in ejbCaller bean) I want to inject an implementation of ejbInterface. I will know which one I need at runtime (i.e. based on some DB value).
I know that one working way to do this is by making the selection at deployment via @Alternative annotation and deployment descriptors but I'd rather make the choice at runtime.
I already tried the @Producer approach but this way I can only inject unmanaged objects (objects I instantiate in the producer and that are not container managed or can be themselves injection points). I have found two workarounds/exploits of producer:
- Produce an un-managed object and pass any managed object (i.e. other beans, entity managers) via a
setup
method in ejbInterface (ejbCaller will have to pass these) - Use a JNDI lookup in the producer and return a managed object
Both workarounds are error-prone and not elegant. Is there a better solution for this?