Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI in Java EE - which Java classes cannot be injected?

I was going through Oracle Java EE 6 Tutorial and under the section "Beans as Injectable Objects", it says

The following kinds of objects can be injected:

(Almost) any Java class

Session beans ......

What would be an example of a Java class that cannot be injected? Is it just some theoretical technical limitation they are mentioning or are there known limitations for the kind of classes that can be injected?

like image 373
senseiwu Avatar asked Jan 22 '14 10:01

senseiwu


1 Answers

From the spec, ch. 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”.

And then the referenced section:

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.

So to sum up: Any Java type (including interfaces, abstract classes) can be a CDI bean, unless it is "normal scoped" and at least one of the following holds true:

  • Does not have a non-private constructor with no parameters
  • Is final/has final methods
  • Is primitive (int, double etc) or array

Normal-scoped (e.g. @Application-, @Session-, @RequestScoped) means it will need to be proxied by the container, thus the above restrictions may be replaced by "is not proxiable". @Dependent and @javax.inject.Singleton are not normal scopes, they are pseudo scopes.

like image 190
Nikos Paraskevopoulos Avatar answered Oct 02 '22 16:10

Nikos Paraskevopoulos