java - Java EE 中的 CDI - 哪些 Java 类不能注入(inject)?

标签 java jakarta-ee cdi

我正在浏览 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)构造函数
  • 是最终的/有最终的方法
  • 是原始类型(intdouble 等)或数组

普通范围(例如@Application-@Session-@RequestScoped)意味着它需要由容器代理,因此上述限制可能会被“不可代理”所取代。 @Dependent@javax.inject.Singleton 不是普通作用域,它们是伪作用域。

关于java - Java EE 中的 CDI - 哪些 Java 类不能注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21280146/

相关文章:

java - EJB 3.0 异常处理

java - Websphere Liberty Base 17 上的 EJBConfigurationException

java - Spring 中的 quartz 作业尚未启动

java - javax.enterprise.context.RequestScoped 在字段上指定时如何工作?

java - 使用 CDI 进行测试,模拟一个 bean

java - 无法在 JSF 托管 bean 中使用 CDI 获取数据库连接

liquibase 中的 Java 代码变更集

java - Spring 启动: Response timestamp is advance 1 hour

java - 使用 Java 流仅通过 lambda 对任何元素执行操作

java - 在 NavigationView 中获取 NullPointerException