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

标签 java static dependency-injection annotations ejb-3.0

我想写这段代码:

@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/

相关文章:

java - 高效的条件查询仅选择查询的第一个和最后一个结果?

JavaFX TableView 禁用复选框

java - 静态嵌套类

scala - 自定义操作中的依赖注入(inject) API

c# - MVVMLight 中的 IoC 容器 - 如何将具体实现传递给指定的元素?

java - Android中如何确定两个 View 的公共(public)父 View

java - 扫描仪双值 - InputMismatchException

c - C函数的原型(prototype)和定义中都需要static关键字吗?

java - 如何在另一个类中调用一个类的main方法?

java - java 中抽象类属性重写导致 null