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

萝らか妹 提交于 2019-12-06 23:05:32

问题


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

回答1:


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.




回答2:


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.




回答3:


I think it's kind a hard to mock annotated EJBs. When using lookup you are able to build some switch according to your environment (test -> LoginMockBean, production -> LoginBean).



来源:https://stackoverflow.com/questions/2085679/ejb3-obtaining-bean-via-injection-vs-lookup-what-are-the-differences-implic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!