@EJB annotation vs JNDI lookup

有些话、适合烂在心里 提交于 2019-12-18 17:25:14

问题


Is there any situation where it's better to use JNDI than to inject a stateless session bean using the @EJB annotation?

We're using JSF 1.2 with Sun Application Server 9.0_01.

Our team is debating which approach is better when using SLSBs in a Managed Bean.

I've read the following questions, but was wondering if there was a situation where lookup is preferred.

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

  • @EJB injection vs lookup - performance issue


回答1:


Is there any situation where it's better to use JNDI than to inject a stateless session bean using the @EJB annotation?

There's no situation where it's better--but situations where it's necessary:

  • when the name to lookup is not known at compile time (I would argue that it's bad design, but that's another issue)
  • when annotations are not supported, e.g. in regular non-managed helper classes and few other cases (We could again argue about whether it's good or bad to depends on EJB in these classes).

If the name to look up is constant and injection is possible, prefer @EJB annotations:

  • Make testing easier
  • Less trouble figuring out local / global JNDI names



回答2:


JNDI lookup might be important in case of SFSB (be sure to access the same instance all the time), but in case of SLSB I am not aware of any cases where JNDI would be "better" in any way.

I'd definitely go with @EJB. It's easier to read (less error-prone code), easier to maintain (you don't care about JNDI namespace location of the bean) and easier to test (no nasty lookup code you need to cut off when performing unit tests).

When talking about performance reasons - I am not 100% sure but I wouldn't be surprised if it'd occur that the application server is in fact doing a JNDI lookup behind the scenes when you use annotations.




回答3:


Is there any situation where it's better to use JNDI than to inject a stateless session bean using the @EJB annotation?

A concrete situation that requires JNDI lookup of a SLSB is described in this question and relative answer: JPA Inheritance and EJB polymorphism. Essentially, when the class name of the SLSB is determined at runtime.



来源:https://stackoverflow.com/questions/12681436/ejb-annotation-vs-jndi-lookup

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