EJB3 - 通过注入和查找获取bean - 有什么区别,含义,陷阱? [英] EJB3 - obtaining bean via injection vs lookup - what are the differences, implications, gotchas?

查看:135
本文介绍了EJB3 - 通过注入和查找获取bean - 有什么区别,含义,陷阱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有两种获取EJB实例的方法:

There are two ways I know of to obtain an EJB instance:


  • 通过@EJB注释在servlet和EJB中进行依赖注入

  • 通过Context.lookup在任何地方查找JNDI

使用中有什么不同,含义和陷阱这些方法中的哪一种?它们是一样的吗?依赖注入比查找更快吗?那么事务处理和对象生命周期管理呢?

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?

我所知道的事情包括:

注释


  • 仅适用于servlet和EJB

  • 方便的语法

  • 容器独立

查找


  • 可以在运行时以编程方式实例化EJB接口的不同实现。

  • 可在任何地方工作 - 例如POJO。

  • 取决于容器的命名约定

推荐答案

两者都达到了相同的效果。这更像是耦合的问题。使用注释,您可以实现松散耦合,并且更容易进行模拟和测试。通过直接查找,您可以依赖于有时可能不方便的初始上下文。

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.

恕我直言查找无处不在。例如,在Glassfish中,只有先前使用 @EJBs(...)在其中一个会话中导入,才能从POJO查找本地EJB。使用POJO的bean。请参阅此讨论。您需要了解本地全局 JNDI之间的区别。

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.

我的建议是:尽可能使用注释。如果POJO需要对EJB的引用,则将其作为参数传递(例如,在构造函数中)。这就是所谓的依赖倒置,无论如何都是一种很好的做法。

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.

这篇关于EJB3 - 通过注入和查找获取bean - 有什么区别,含义,陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆