gpt4 book ai didi

java - 注入(inject)静态EJB,废话?

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:10 24 4
gpt4 key购买 nike

我想写这段代码:

@Stateless
public class MyEjb
{
@EJB
private static MyOtherEjbWhichIWantStatic myOtherEjb;
}

出于各种原因,我想在我的类中注入(inject)一个 EJB 作为静态元素,这对我来说很有意义。

不幸的是,Java 对此不是很满意

com.sun.enterprise.container.common.spi.util.InjectionException: Illegal use of static field private static MyOtherEjbWhichIWantStatic myOtherEjb on class that only supports instance-based injection

我不明白,为什么我不能将静态 EJB 注入(inject)到另一个 EJB 中?

最佳答案

正如其他人所指出的,规范不允许这样做,简短的版本是 @EJB 注释仅支持具有 main()< 的类中的静态成员 函数(请参阅 EJB 3.0 规范和应用程序客户端容器)。

为什么会这样?首先,在 EJB 中完全禁止读/写静态字段(这是 EJB 限制的一部分)。来自 Why can't I use nonfinal static fields in my enterprise bean?

Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). Updating a static class field implies an intent to share the field's value among all instances of the class. But if a class is running in several JVMs simultaneously, only those instances running in the same JVM as the updating instance will have access to the new value. In other words, a nonfinal static class field will behave differently if running in a single JVM, than it will running in multiple JVMs. The EJB container reserves the option of distributing enterprise beans across multiple JVMs (running on the same server, or on any of a cluster of servers). Nonfinal static class fields are disallowed because enterprise bean instances will behave differently depending on whether or not they are distributed.

It is acceptable practice to use static class fields if those fields are marked as final. Since final fields cannot be updated, instances of the enterprise bean can be distributed by the container without concern for those fields' values becoming unsynchronized.

但是虽然允许使用只读静态字段,但这不适合 EJB。无状态 EJB 可能被合并,容器可能决定销毁它们(这是特定于实现的)并且您希望让容器选择您要使用的实例,尤其是在分布式环境中。换句话说,永远不要假设你被绑定(bind)到一个特定的实例。

所以最后,是的,这是胡说八道。

关于java - 注入(inject)静态EJB,废话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195365/

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