gpt4 book ai didi

java - 在 POJO 中使用 EJB 注入(inject)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:31 24 4
gpt4 key购买 nike

我知道使用@EJB 注释的注入(inject)只能在 EJB 类、servlet 或 JSF 托管 bean 中使用,但同时我需要在 POJO 类中有一些注入(inject)业务接口(interface)的实例,所以我想到了执行以下操作:

在我的 JSF 托管 bean 中

@EJB BusinessInterfaceLocal businessInterface;

private void someMethod(){
PojoInterface pojo = new PojoClass(this.businessInterface);
}

在我的 POJO 类中我有这个构造函数

BusinessInterfaceLocal businessInterface;    

public PojoClass(BusinessInterfaceLocal businessInterface){
this.businessInterface = businessInterface;

//The following throws a Null Pointer Exception
this.businessInterface.someMethodCall();
}

上面的方法不应该正常工作吗?但事实并非如此,PojoClass 中的 businessInterface 对象被评估为 null,从而引发空指针异常。

我希望有人能指出我做错了什么。

提前致谢。

最佳答案

验证

是否可以在注入(inject) EJB 之前创建 PojoClass。我的意思是,你在哪里调用“someMethod”?它在托管 bean 的构造函数中吗?变量不会丢失其引用值。

您说您可以看到托管 bean 中的 BusinessInterfaceLocalbean 不为空,您可以验证您在检查后创建了 Pojo 吗?

替代解决方案:

解决方案 1您可以将 POJO 用作无状态 bean,我认为这样做没有任何问题,除非您当然尝试在 EE 容器之外使用 POJO,从外观上看并非如此。

使 POJO 无状态将使您能够注入(inject) EJB。

解决方案 2或者 JNDI 查找,实现如下:

@Stateless(name="myEJB")
public class MyEJB {

public void ejbMethod() {
// business logic
}

}

public class TestEJB {

public static void main() {
MyEJB ejbRef = (MyEJB) new InitialContext().lookup("java:comp/env/myEJB");
ejbRef.ejbMethod();
}
}

关于java - 在 POJO 中使用 EJB 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com