我正在浏览 Oracle Java EE 6 Tutorial在“Beans as Injectable Objects”部分下,它说
The following kinds of objects can be injected:
(Almost) any Java class
Session beans ......
无法注入(inject)的 Java 类的示例是什么?他们提到的只是一些理论上的技术限制,还是可以注入(inject)的类类型存在已知限制?
最佳答案
来自spec , channel 。 2.2.1:
Almost any Java type may be a bean type of a bean:
- A bean type may be an interface, a concrete class or an abstract class, and may be declared final or have final methods.
- A bean type may be a parameterized type with actual type parameters and type variables.
- A bean type may be an array type. Two array types are considered identical only if the element type is identical.
- A bean type may be a primitive type. Primitive types are considered to be identical to their corresponding wrapper types in java.lang.
- A bean type may be a raw type.
A type variable is not a legal bean type. A parameterized type that contains a wildcard type parameter is not a legal bean type.
Note that certain additional restrictions are specified in Section 5.4.1, “Unproxyable bean types” for beans with a normal scope, as defined in Section 6.3, “Normal scopes and pseudo-scopes”.
然后是引用部分:
Certain legal bean types cannot be proxied by the container:
- classes which don't have a non-private constructor with no parameters,
- classes which are declared final or have final methods,
- primitive types,
- and array types.
总结一下:任何 Java 类型(包括接口(interface)、抽象类)都可以是 CDI bean,除非它是“正常作用域”并且至少满足以下条件之一: p>
- 没有不带参数的非私有(private)构造函数
- 是最终的/有最终的方法
- 是原始类型(
int
、double
等)或数组
普通范围(例如@Application-
、@Session-
、@RequestScoped
)意味着它需要由容器代理,因此上述限制可能会被“不可代理”所取代。 @Dependent
和 @javax.inject.Singleton
不是普通作用域,它们是伪作用域。
关于java - Java EE 中的 CDI - 哪些 Java 类不能注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21280146/