Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJB3 - obtaining bean via injection vs lookup - what are the differences, implications, gotchas?

Tags:

java

ejb-3.0

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
like image 463
Conor Avatar asked Jan 18 '10 11:01

Conor


2 Answers

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.

like image 76
ewernli Avatar answered Nov 08 '22 23:11

ewernli


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.

like image 28
axtavt Avatar answered Nov 09 '22 00:11

axtavt