There are two ways I know of to obtain an EJB instance:
- dependency injection in servlets and EJBs via the @EJB annotation
- JNDI lookup via Context.lookup anywhere
What are the differences, implications and gotchas in using either of these approaches? Are they the same? Is dependency injection faster than lookup? What about transaction handling and object lifecycle management?
Things I'm aware of include:
annotation
- works with servlets and and EJBs only
- convenient syntax
- container independent
lookup
- can instantiate different implementations of the EJB interface programatically at run time.
- works from anywhere - e.g. POJOs.
- depends on naming convention of container
MyBean bean = new MyBean(); bean.injectedBean = new Mock()
. Hooking in the lookup is more complicated, especially if code depends onnew InitialContext()
. How do you return a special version of the context for your tests? – Perfectible