3

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?

Tasos P.
  • 3,994
  • 2
  • 21
  • 41
  • 1
    I'd definitely go with the second choice. Have a look at a similar situation here: http://stackoverflow.com/questions/12512571/jpa-inheritance-and-ejb-polymorphism – perissf Oct 24 '12 at 08:17
  • Thank you very much for the pointer! I agree that the first approach is more dangerous. I'll work on the JNDI lookup and see how well it goes. – Tasos P. Oct 25 '12 at 06:21
  • 1
    Haven't looked at Instance from CDI? – LightGuard Oct 26 '12 at 04:36
  • This definitely looks more elegant for me. I'm afraid I never heard of this feature of CDI (shame on me) but I'll explore it. I suppose that if I `@Inject @Any Instance myEJBs` and inspect each element in myEJBs, I can choose the EJB to return from my producer. – Tasos P. Oct 26 '12 at 05:47

1 Answers1

1

Just inject the BeanManager and use

javax.enterprise.inject.spi.BeanManager.getBeans(Type, Annotation...)

at runtime

roehrijn
  • 1,387
  • 1
  • 11
  • 20