Java Reference
In-Depth Information
Next, the javax.inject.Inject annotation ( @Inject ) must be used to denote the class being injected by
annotating a class variable of the object type. For instance, if you want to inject a Java object of TypeA , you would
declare a class variable of type TypeA and annotate it with @Inject , as follows:
@Inject
TypeA myTypeVar;
Once the injection is performed, the declared variable can be utilized throughout the class because it is a direct
reference to the original class of the specified Java type. By defining a specific scope to the injection bean, you can
indicate whether an injected object will cause the instantiation of a new object of that type or whether it will look
up an existing object of that type and reuse it. By far, one of the most convenient and useful cases for using CDI is
the ability to inject a managed bean into another object and make use of its current state, as if its contents existed
everywhere.
CDI provides type-safe injection because there is no need to specify a String-based name in order to instantiate
or refer to another object. By maintaining declared variables that are used as points of injection, the variable name
itself provides for strong typing and thus reduces the number of errors that may arise. A couple new features have
been added to make dependency injection even more useful, and the following sections aim to describe those
enhancements.
Injection of Bean Metadata
The Bean , Interceptor , and Decorator interfaces provide metadata about a bean. As of CDI 1.1, it is possible for bean
metadata to be injected into a bean instance. To obtain information using the Bean interface, inject it into the bean
that needs to use it, and then call upon its methods to obtain the desired information. The following bean types can be
injected using the Bean type:
@Dependent , @Default as the qualifier, and type Bean
A bean with scope
@Dependent , @Default as the qualifier, and type Interceptor
A bean with scope
@Dependent , @Default as the qualifier, and type Decorator
Additionally, beans that allow interceptors and decorators can obtain information about the beans that they
intercept and/or decorate. A definition error occurs if an Interceptor or Decorator instance is injected into any bean
instance other than an interceptor or decorator instance, respectively.
The following example demonstrates the use of the Bean interface to retrieve metadata regarding the bean named
OrderProcessor :
A bean with scope
@Named("Order")
public class OrderProcessor {
@Inject Bean<OrderProcessor> bean;
public String getBeanName(){
return bean.getName();
}
public Class<? extends Annotation> getScope(){
return bean.getScope();
}
}
 
Search WWH ::




Custom Search