There are two ways I know of to obtain an EJB instance:
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
lookup
Both achieve the same result. It's more a matter of coupling. With annotation, you achieve loose coupling and it's easier to mock and test. With direct lookup, you depend on the initial context which may be unconvenient sometimes.
IMHO lookup does not work everywhere. For instance in Glassfish, a lookup on a local EJB from a POJO will work only if has been "imported" previously with @EJBs(...)
on one of the session beans that uses the POJO. See this discussion. You need to understand the difference between the local and global JNDI for that.
My advice would be: use annotation as much as possible. If a POJO need a reference to an EJB, pass it as parameter (e.g. in the constructor). That's called dependency inversion and is anyway a good practice.
Lookup depends on presence of JNDI implementation, that is, you have to configure JNDI implementation in order to run unit tests, then annotated fields can be configured manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With