java - 在 JBoss 7.2 中查找 SessionContext

标签 java exception jboss7.x

出于各种原因,我需要手动查找 SessionContext。在JBoss5中,解决方案

InitialContext initialContext = new InitialContext();
SessionContext sessionContext = (SessionContext) initialContext.lookup("java:comp/EJBContext");

对医疗效果很好,但从 JBoss 7 开始,我得到了

javax.naming.NameNotFoundException: EJBContext -- service jboss.naming.context.java.global.EJBContext

JBoss 7.2 中查找上下文的方式是否发生了变化,或者我的部署是否缺少任何重要内容?作为引用,标准注入(inject)工作正常,这是唯一失败的查找。或者我是否做了一些非常错误的事情(除了执行 SessionContext 的手动查找之外)?

最佳答案

根据Java EJB的规范(这个适用于 EJB 3.2。但与上一个 EJB 3.x 相比,EJBContext 没有任何变化),您可以使用注释 EJBContext 注入(inject)到您的组件中@Resource 或通过查找手动(第 11.15 节):

The container must make a component’s EJBContext interface available either through injection using the Resource annotation or in JNDI under the name java:comp/EJBContext

查找 EJB 资源的标准方法是通过 EJBContext.lookup 方法,但也有 JNDI 方法,如果您还没有 EJBContext ,这是唯一的可能性:

Context initCtx = new InitialContext();
EJBContext ejbCtx = (EJBContext) initCtx.lookup("java:comp/EJBContext");

这正是您所做的,那么有什么问题吗?有两件事,我不确定哪一件事。首先,通过手动查找,有时需要在类级别将资源分配给带有注释的组件:

@Resource(name = "EJBContext", type = javax.ejb.EJBContext)
public class MyComponent {
...
}

但我不确定 EJBContext 是否也需要它,我想不需要。第二件事,更重要和关键 - 再次根据规范:

EJBContext objects accessed through the naming environment are only valid within the bean instance that performed the lookup.

这一节是第 11.15.1 节,下一节是第 11.15.2 节:

The Container Provider is responsible for providing an appropriate EJBContext object to the refer- encing component. The object returned must be of the appropriate specific type for the bean requesting injection or performing the lookup—that is, the Container Provider must return an instance of the SessionContext interface to referencing session beans and an instance of the MessageDrivenCon- text interface to message-driven beans.

这两者都意味着EJBContext的注入(inject)和查找仅在Enterprise Java Beans中有效,因此那些用@MessageDriven@Stateful注释的code>、@Singleton@Stateless(或在部署描述 rune 件中描述为 EJB,也称为 EJB 2.x 规范)。也许您的组件不是有效的 EJB,这就是查找不起作用的原因?当然这只是建议。

还有一种获取EJBContext(更准确地说是SessionContext)的可能性。您的组件应该实现具有 setSessionContext(SessionContext sessionContext) 方法的 SessionBean 接口(interface)。每次使用组件时(在某处注入(inject)、由客户端调用或超时,特别是在创建组件时),EJB 容器都应该调用此方法,并且在该方法中,您应该将 sessionContext 参数分配给 bean 的字段。

关于java - 在 JBoss 7.2 中查找 SessionContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22832640/

相关文章:

java - Java泛型类——如何理解?

java - JBoss 中枚举的每个 NetworkInterface 总是 isUp

python - 与其他异常分开处理特定异常(例如 ENOENT)

web-applications - 在 JBoss 7 Final 上部署应用程序的问题

ejb-3.0 - EJB 远程查找失败并出现 javax.naming.NameNotFoundException

java - 在java中,有没有一种方法可以结合String.contain()和String.equals()来在给定另一个字符时打印出某个字符?

java - 为什么StockWatcher.java在onModuleLoad中使用类变量而不是局部变量?

java - 使用注入(inject)的bean方法返回值作为@Cacheable注释中的键

C++ 在捕获异常后进行清理的标准方法是什么?

java - 使用数组参数的参数化 JUnit 测试中的反射异常