Debian Codegraph @

spec/src/main/doc/injectionelresolution.asciidoc

raw
1 [[injection_el_resolution]]
2
3 == Dependency injection, lookup and EL
4
5 The container injects references to contextual instances to the following kinds of _injection point_:
6
7 * Any injected field of a bean class
8 * Any parameter of a bean constructor, bean initializer method, producer method or disposer method
9 * Any parameter of an observer method, except for the event parameter
10
11
12 References to contextual instances may also be obtained by programmatic lookup or by Unified EL expression evaluation.
13
14 In general, a bean type or bean name does not uniquely identify a bean. When resolving a bean at an injection point, the container considers bean type, qualifiers and selected alternatives. When resolving a name in an EL expression, the container considers the bean name and selected alternatives. This allows bean developers to decouple type from implementation.
15
16 The container is required to support circularities in the bean dependency graph where at least one bean participating in every circular chain of dependencies has a normal scope, as defined in <<normal_scope>>. The container is not required to support circular chains of dependencies where every bean participating in the chain has a pseudo-scope.
17
18 [[selection]]
19
20 === Modularity
21
22 Beans and their clients may be deployed in _modules_ in a module architecture such as the Java EE environment. In a module architecture, certain modules are considered _bean archives_. In the Java EE module architecture, any Java EE module or library is a module. The Java EE module or library is a bean archive if it contains a +beans.xml+ file, as defined in <<bean_archive>>.
23
24 A bean packaged in a certain module is available for injection, lookup and EL resolution to classes and JSP/JSF pages packaged in some other module if and only if the bean class of the bean is required to be _accessible_ to the other module by the class accessibility requirements of the module architecture. In the Java EE module architecture, a bean class is accessible in a module if and only if it is required to be accessible according to the class loading requirements defined by the Java EE platform specification.
25
26 Note that, in some Java EE implementations, a bean class might be accessible to some other class even when this is not required by the Java EE platform specification. For the purposes of this specification, a class is not considered accessible to another class unless accessibility is explicitly required by the Java EE platform specification.
27
28 An alternative is not available for injection, lookup or EL resolution to classes or JSP/JSF pages in a module unless the module is a bean archive and the alternative is explicitly _selected_ for the bean archive or the application.
29
30 [[declaring_selected_alternatives]]
31
32 ==== Declaring selected alternatives
33
34 This specification defines two methods of selecting alternatives. From Contexts and Dependency Injection 1.1 onwards the +@Priority+ annotation allows an alternative to be selected for an entire application. Contexts and Dependency Injection 1.0 allowed only for an alternative to be selected for a bean archive.
35
36 [[declaring_selected_alternatives_application]]
37
38 ===== Declaring selected alternatives for an application
39
40 An alternative may be given a priority for the application:
41
42 * by placing the +@Priority+ annotation on the bean class of a managed bean or session bean, or
43 * by placing the +@Priority+ annotation on the bean class that declares the producer method, field or resource.
44
45 [[declaring_selected_alternatives_bean_archive]]
46
47 ===== Declaring selected alternatives for a bean archive
48
49
50 An alternative may be explicitly declared using the +<alternatives>+ element of the +beans.xml+ file of the bean archive. The +<alternatives>+ element contains a list of bean classes and stereotypes. An alternative is selected for the bean archive if either:
51
52 * the alternative is a managed bean or session bean and the bean class of the bean is listed,
53 * the alternative is a producer method, field or resource, and the bean class that declares the method or field is listed, or
54 * any +@Alternative+ stereotype of the alternative is listed.
55
56 [source,xml]
57 ----
58 <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
59 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
60 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
61 <alternatives>
62 <class>com.acme.myfwk.InMemoryDatabase</class>
63 <stereotype>com.acme.myfwk.Mock</stereotype>
64 <stereotype>com.acme.site.Australian</stereotype>
65 </alternatives>
66 </beans>
67 ----
68
69 Each child +<class>+ element must specify the name of a bean class of an alternative bean. If there is no bean whose bean class has the specified name, or if no bean whose bean class has the specified name is an alternative, the container automatically detects the problem and treats it as a deployment problem.
70
71 Each child +<stereotype>+ element must specify the name of an +@Alternative+ stereotype annotation. If there is no annotation with the specified name, or the annotation is not an +@Alternative+ stereotype, the container automatically detects the problem and treats it as a deployment problem.
72
73 If the same type is listed twice under the +<alternatives>+ element, the container automatically detects the problem and treats it as a deployment problem.
74
75 For a custom implementation of the +Bean+ interface defined in <<bean>>, the container calls +isAlternative()+ to determine whether the bean is an alternative, and +getBeanClass()+ and +getStereotypes()+ to determine whether an alternative is selected in a certain bean archive.
76
77 [[enablement]]
78
79 ==== Enabled and disabled beans
80
81 A bean is said to be _enabled_ if:
82
83 * it is deployed in a bean archive, and
84 * it is not a producer method or field of a disabled bean, and
85 * it is not specialized by any other enabled bean, as defined in <<specialization>>, and either
86 * it is not an alternative, or it is a selected alternative of at least one bean archive or the application.
87
88
89 Otherwise, the bean is said to be disabled.
90
91 Note that <<new>> defines a special rule that determines whether a +@New+ qualified bean is enabled or disabled. This rule applies as only to +@New+ qualified beans, as an exception to the normal rule defined here.
92
93 [[inconsistent_specialization]]
94
95 ==== Inconsistent specialization
96
97 Suppose an enabled bean X specializes a second bean Y. If there is another enabled bean that specializes Y we say that _inconsistent specialization_ exists. The container automatically detects inconsistent specialization and treats it as a deployment problem.
98
99 [[inter_module_injection]]
100
101 ==== Inter-module injection
102
103 A bean is _available for injection_ in a certain module if:
104
105 * the bean is not an interceptor or decorator,
106 * the bean is enabled,
107 * the bean is either not an alternative, or the module is a bean archive and the bean is a selected alternative of the bean archive, or the bean is a selected alternative of the application, and
108 * the bean class is required to be accessible to classes in the module, according to the class accessibility requirements of the module architecture.
109
110
111 For a custom implementation of the +Bean+ interface defined in <<bean>>, the container calls +getBeanClass()+ to determine the bean class of the bean and +InjectionPoint.getMember()+ and then +Member.getDeclaringClass()+ to determine the class that declares an injection point.
112
113 [[typesafe_resolution]]
114
115 === Typesafe resolution
116
117 The process of matching a bean to an injection point is called _typesafe resolution_. Typesafe resolution usually occurs at application initialization time, allowing the container to warn the user if any enabled beans have unsatisfied or unresolvable ambiguous dependencies.
118
119 [[performing_typesafe_resolution]]
120
121 ==== Performing typesafe resolution
122
123 The container considers bean type and qualifiers when resolving a bean to be injected to an injection point. The type and qualifiers of the injection point are called the _required type_ and _required qualifiers_.
124
125 A bean is _assignable_ to a given injection point if:
126
127 * The bean has a bean type that matches the required type. For this purpose, primitive types are considered to match their corresponding wrapper types in +java.lang+ and array types are considered to match only if their element types are identical. Parameterized and raw types are considered to match if they are identical or if the bean type is _assignable_ to the required type, as defined in <<assignable_parameters>> or <<delegate_assignable_parameters>>.
128 * The bean has all the required qualifiers. If no required qualifiers were explicitly specified, the container assumes the required qualifier +@Default+. A bean has a required qualifier if it has a qualifier with (a) the same type and (b) the same annotation member value for each member which is not annotated [email protected]+.
129
130
131 A bean is eligible for injection to a certain injection point if:
132
133 * it is available for injection in the module that contains the class that declares the injection point, and
134 * it is assignable to the injection point (using <<assignable_parameters>>).
135
136
137 For a custom implementation of the +Bean+ interface defined in <<bean>>, the container calls +getTypes()+ and +getQualifiers()+ to determine the bean types and qualifiers.
138
139 [[unsatisfied_and_ambig_dependencies]]
140
141 ==== Unsatisfied and ambiguous dependencies
142
143 An _unsatisfied dependency_ exists at an injection point when no bean is eligible for injection to the injection point. An _ambiguous dependency_ exists at an injection point when multiple beans are eligible for injection to the injection point.
144
145 Note that an unsatisfied or ambiguous dependency cannot exist for a decorator delegate injection point, defined in <<delegate_attribute>>.
146
147 When an ambiguous dependency exists, the container attempts to resolve the ambiguity. The container eliminates all eligible beans that are not alternatives, except for producer methods and fields of beans that are alternatives. If:
148
149 * there is exactly one bean remaining, the container will select this bean, and the ambiguous dependency is called resolvable.
150 * all the beans left are alternatives with a priority, or producer methods or fields of beans that are alternatives with a priority, then the container will determine the highest priority value, and eliminate all beans, except for alternatives with the highest priority and producer methods and fields of alternatives with the highest priority value. If there is exactly one bean remaining, the container will select this bean, and the ambiguous dependency is called resolvable.
151
152 The container must validate all injection points of all enabled beans, all observer methods, all disposer methods and all other Java EE component classes supporting injection when the application is initialized to ensure that there are no unsatisfied or unresolvable ambiguous dependencies. If an unsatisfied or unresolvable ambiguous dependency exists, the container automatically detects the problem and treats it as a deployment problem.
153
154 For a custom implementation of the +Bean+ interface defined in <<bean>>, the container calls +getInjectionPoints()+ to determine the set of injection points.
155
156 [[legal_injection_point_types]]
157
158 ==== Legal injection point types
159
160 Any legal bean type, as defined in <<legal_bean_types>> may be the required type of an injection point. Furthermore, the required type of an injection point may contain a wildcard type parameter. However, a type variable is not a legal injection point type.
161
162 If an injection point type is a type variable, the container automatically detects the problem and treats it as a definition error.
163
164 [[assignable_parameters]]
165
166 ==== Assignability of raw and parameterized types
167
168 A parameterized bean type is considered assignable to a raw required type if the raw types are identical and all type parameters of the bean type are either unbounded type variables or +java.lang.Object+.
169
170 A parameterized bean type is considered assignable to a parameterized required type if they have identical raw type and for each parameter:
171
172 * the required type parameter and the bean type parameter are actual types with identical raw type, and, if the type is parameterized, the bean type parameter is assignable to the required type parameter according to these rules, or
173 * the required type parameter is a wildcard, the bean type parameter is an actual type and the actual type is assignable to the upper bound, if any, of the wildcard and assignable from the lower bound, if any, of the wildcard, or
174 * the required type parameter is a wildcard, the bean type parameter is a type variable and the upper bound of the type variable is assignable to or assignable from the upper bound, if any, of the wildcard and assignable from the lower bound, if any, of the wildcard, or
175 * the required type parameter is an actual type, the bean type parameter is a type variable and the actual type is assignable to the upper bound, if any, of the type variable, or
176 * the required type parameter and the bean type parameter are both type variables and the upper bound of the required type parameter is assignable to the upper bound, if any, of the bean type parameter.
177
178
179 For example, +Dao+ is eligible for injection to any injection point of type +@Default Dao<Order>+, +@Default Dao<User>+, +@Default Dao<?>+, +@Default Dao<? extends Persistent>+ or +@Default Dao<X extends Persistent>+ where +X+ is a type variable.
180
181 [source, java]
182 ----
183 public class Dao<T extends Persistent> { ... }
184 ----
185
186 Furthermore, +UserDao+ is eligible for injection to any injection point of type +@Default Dao<User>+, +@Default Dao<?>+, +@Default Dao<? extends Persistent>+ or +@Default Dao<? extends User>+.
187
188 [source, java]
189 ----
190 public class UserDao extends Dao<User> { ... }
191 ----
192
193 A raw bean type is considered assignable to a parameterized required type if the raw types are identical and all type parameters of the required type are either unbounded type variables or java.lang.Object.
194
195 Note that a special set of rules, defined in <<delegate_assignable_parameters>>, apply if and only if the injection point is a decorator delegate injection point.
196
197 [[null]]
198
199 ==== Primitive types and null values
200
201 For the purposes of typesafe resolution and dependency injection, primitive types and their corresponding wrapper types in the package +java.lang+ are considered identical and assignable. If necessary, the container performs boxing or unboxing when it injects a value to a field or parameter of primitive or wrapper type.
202
203 If an injection point of primitive type resolves to a producer method or producer field that returns a null value at runtime, the container must inject the primitive type's default value as defined by the Java Language Specification.
204
205 [[qualifier_annotation_members]]
206
207 ==== Qualifier annotations with members
208
209 Qualifier types may have annotation members.
210
211 [source, java]
212 ----
213 @PayBy(CHEQUE) class ChequePaymentProcessor implements PaymentProcessor { ... }
214 ----
215
216 [source, java]
217 ----
218 @PayBy(CREDIT_CARD) class CreditCardPaymentProcessor implements PaymentProcessor { ... }
219 ----
220
221 Then only +ChequePaymentProcessor+ is a candidate for injection to the following attribute:
222
223 [source, java]
224 ----
225 @Inject @PayBy(CHEQUE) PaymentProcessor paymentProcessor;
226 ----
227
228 On the other hand, only +CreditCardPaymentProcessor+ is a candidate for injection to this attribute:
229
230 [source, java]
231 ----
232 @Inject @PayBy(CREDIT_CARD) PaymentProcessor paymentProcessor;
233 ----
234
235 The container calls the +equals()+ method of the annotation member value to compare values.
236
237 An annotation member may be excluded from consideration using the +@Nonbinding+ annotation.
238
239 [source, java]
240 ----
241 @Qualifier
242 @Retention(RUNTIME)
243 @Target({METHOD, FIELD, PARAMETER, TYPE})
244 public @interface PayBy {
245 PaymentMethod value();
246 @Nonbinding String comment() default "";
247 }
248 ----
249
250 Array-valued or annotation-valued members of a qualifier type should be annotated +@Nonbinding+ in a portable application. If an array-valued or annotation-valued member of a qualifier type is not annotated +@Nonbinding+, non-portable behavior results.
251
252 [[multiple_qualifiers]]
253
254 ==== Multiple qualifiers
255
256 A bean class or producer method or field may declare multiple qualifiers.
257
258 [source, java]
259 ----
260 @Synchronous @PayBy(CHEQUE) class ChequePaymentProcessor implements PaymentProcessor { ... }
261 ----
262
263 Then +ChequePaymentProcessor+ would be considered a candidate for injection into any of the following attributes:
264
265 [source, java]
266 ----
267 @Inject @PayBy(CHEQUE) PaymentProcessor paymentProcessor;
268 ----
269
270 [source, java]
271 ----
272 @Inject @Synchronous PaymentProcessor paymentProcessor;
273 ----
274
275 [source, java]
276 ----
277 @Inject @Synchronous @PayBy(CHEQUE) PaymentProcessor paymentProcessor;
278 ----
279
280 A bean must declare _all_ of the qualifiers that are specified at the injection point to be considered a candidate for injection.
281
282 [[name_resolution]]
283
284 === EL name resolution
285
286 The process of matching a bean to a name used in EL is called _name resolution_. Since there is no typing information available in EL, the container may consider only the bean name. Name resolution usually occurs at runtime, during EL expression evaluation.
287
288 An EL name resolves to a bean if:
289
290 * the bean has the given bean name, and
291 * the bean is available for injection in the war containing the JSP or JSF page with the EL expression.
292
293 For a custom implementation of the +Bean+ interface defined in <<bean>>, the container calls +getName()+ to determine the bean name.
294
295 [[ambig_names]]
296
297 ==== Ambiguous EL names
298
299 An _ambiguous EL name_ exists in an EL expression when an EL name resolves to multiple beans. When an ambiguous EL name exists, the container attempts to resolve the ambiguity. The container eliminates all eligible beans that are not alternatives selected for the bean archive or selected for the application, except for producer methods and fields of beans that are alternatives. If:
300
301 * there is exactly one bean remaining, the container will select this bean, and the ambiguous dependency is called _resolvable_.
302 * all the beans left are alternatives with a priority, then the container will determine the highest priority value, and eliminate all beans, except for producer methods and fields of beans that are alternatives with the highest priority value. If there is exactly one bean remaining, the container will select this bean, and the ambiguous dependency is called _resolvable_.
303
304 All unresolvable ambiguous EL names are detected by the container when the application is initialized. Suppose two beans are both available for injection in a certain war, and either:
305
306 * the two beans have the same bean name and the name is not resolvable, or
307 * the bean name of one bean is of the form +x.y+, where +y+ is a valid bean name, and +x+ is the bean name of the other bean,
308
309
310 the container automatically detects the problem and treats it as a deployment problem.
311
312 [[client_proxies]]
313
314 === Client proxies
315
316 An injected reference, or reference obtained by programmatic lookup, is usually a _contextual reference_ as defined by <<contextual_reference>>.
317
318 A contextual reference to a bean with a normal scope, as defined in <<normal_scope>>, is not a direct reference to a contextual instance of the bean (the object returned by +Contextual.create()+). Instead, the contextual reference is a _client proxy_ object. A client proxy implements/extends some or all of the bean types of the bean and delegates all method calls to the current instance (as defined in <<normal_scope>>) of the bean.
319
320 There are a number of reasons for this indirection:
321
322 * The container must guarantee that when any valid injected reference to a bean of normal scope is invoked, the invocation is always processed by the current instance of the injected bean. In certain scenarios, for example if a request scoped bean is injected into a session scoped bean, or into a servlet, this rule requires an indirect reference. (Note that the +@Dependent+ pseudo-scope is not a normal scope.)
323 * The container may use a client proxy when creating beans with circular dependencies. This is only necessary when the circular dependencies are initialized via a managed bean constructor or producer method parameter. (Beans with scope +@Dependent+ never have circular dependencies.)
324 * Finally, client proxies may be passivated, even when the bean itself may not be. Therefore the container must use a client proxy whenever a bean with normal scope is injected into a bean with a passivating scope, as defined in <<passivating_scope>>. (On the other hand, beans with scope +@Dependent+ must be serialized along with their client.)
325
326
327 Client proxies are never required for a bean whose scope is a pseudo-scope such as +@Dependent+.
328
329 Client proxies may be shared between multiple injection points. For example, a particular container might instantiate exactly one client proxy object per bean. (However, this strategy is not required by this specification.)
330
331 [[client_proxy_invocation]]
332
333 ==== Client proxy invocation
334
335 Every time a method of the bean is invoked upon a client proxy, the client proxy must:
336
337 * obtain a contextual instance of the bean, as defined in <<contextual_instance>>, and
338 * invoke the method upon this instance.
339
340
341 If the scope is not active, as specified in <<active_context>>, the client proxy rethrows the +ContextNotActiveException+ or +IllegalStateException+.
342
343 The behavior of all methods declared by +java.lang.Object+, except for +toString()+, is undefined for a client proxy. Portable applications should not invoke any method declared by +java.lang.Object+, except for +toString()+, on a client proxy.
344
345 [[injection]]
346
347 === Dependency injection
348
349 From time to time the container instantiates beans and other Java EE component classes supporting injection. The resulting instance may or may not be a _contextual instance_ as defined by <<contextual_instance>>.
350
351 The container is required to perform dependency injection whenever it creates one of the following contextual objects:
352
353 * contextual instances of session beans, and
354 * contextual instances of managed beans.
355
356
357 The container is also required to perform dependency injection whenever it instantiates any of the following non-contextual objects:
358
359 * non-contextual instances of session beans (for example, session beans obtained by the application from JNDI or injected using +@EJB+),
360 * non-contextual instances of managed beans, and
361 * instances of any other Java EE component class supporting injection.
362
363 A Java EE 5 container is not required to support injection for non-contextual objects.
364
365 The container interacts with instances of beans and other Java EE component classes supporting injection by calling methods and getting and setting field values.
366
367 The object injected by the container may not be a direct reference to a contextual instance of the bean. Instead, it is an injectable reference, as defined by <<injectable_reference>>.
368
369 [[instantiation]]
370
371 ==== Injection using the bean constructor
372
373 When the container instantiates a managed bean or session bean with a constructor annotated +@Inject+, the container calls this constructor, passing an injectable reference to each parameter. If there is no constructor annotated +@Inject+, the container calls the constructor with no parameters.
374
375 [[fields_initializer_methods]]
376
377 ==== Injection of fields and initializer methods
378
379 When the container creates a new instance of a managed bean, session bean, or of any other Java EE component class supporting injection the container must:
380
381 * Initialize the values of all injected fields. The container sets the value of each injected field to an injectable reference.
382 * Call all initializer methods, passing an injectable reference to each parameter.
383
384
385 The container must ensure that:
386
387 * Initializer methods declared by a class X in the type hierarchy of the bean are called after all injected fields declared by X or by superclasses of X have been initialized, and after all Java EE component environment resource dependencies declared by X or by superclasses of X have been injected.
388 * Any +@PostConstruct+ callback declared by a class X in the type hierarchy of the bean is called after all initializer methods declared by X or by superclasses of X have been called, after all injected fields declared by X or by superclasses of X have been initialized, and after all Java EE component environment resource dependencies declared by X or by superclasses of X have been injected.
389 * Any servlet +init()+ method is called after all initializer methods have been called, all injected fields have been initialized and all Java EE component environment resource dependencies have been injected.
390
391
392 [[dependent_objects_destruction]]
393
394 ==== Destruction of dependent objects
395
396 When the container destroys an instance of a bean or of any Java EE component class supporting injection, the container destroys all dependent objects, as defined in <<dependent_destruction>>, after the +@PreDestroy+ callback completes and after the servlet +destroy()+ method is called.
397
398 [[producer_or_disposer_methods_invocation]]
399
400 ==== Invocation of producer or disposer methods
401
402 When the container calls a producer or disposer method, the behavior depends upon whether the method is static or non-static:
403
404 * If the method is static, the container must invoke the method.
405 * Otherwise, if the method is non-static, the container must:
406 * Obtain a contextual instance of the bean which declares the method, as defined by <<contextual_instance>>.
407 * Invoke the method upon this instance, as a business method invocation, as defined in <<biz_method>>.
408
409
410
411
412 The container passes an injectable reference to each injected method parameter. The container is also responsible for destroying dependent objects created during this invocation, as defined in <<dependent_destruction>>.
413
414 [[producer_fields_access]]
415
416 ==== Access to producer field values
417
418 When the container accesses the value of a producer field, the value depends upon whether the field is static or non-static:
419
420 * If the producer field is static, the container must access the field value.
421 * Otherwise, if the producer field is non-static, the container must:
422 * Obtain an contextual instance of the bean which declares the producer field, as defined by <<contextual_instance>>.
423 * Access the field value of this instance.
424
425
426
427
428 [[observers_method_invocation]]
429
430 ==== Invocation of observer methods
431
432 When the container calls an observer method (defined in <<observer_methods>>), the behavior depends upon whether the method is static or non-static:
433
434 * If the observer method is static, the container must invoke the method.
435 * Otherwise, if the observer method is non-static, the container must:
436 * Obtain a contextual instance of the bean which declares the observer method according to <<contextual_instance>>. If this observer method is a conditional observer method, obtain the contextual instance that already exists, only if the scope of the bean that declares the observer method is currently active, without creating a new contextual instance.
437 * Invoke the observer method on the resulting instance, if any, as a business method invocation, as defined in <<biz_method>>.
438
439
440
441
442 The container must pass the event object to the event parameter and an injectable instance to each injected method parameter. The container is also responsible for destroying dependent objects created during this invocation, as defined in <<dependent_destruction>>.
443
444 [[injection_point]]
445
446 ==== Injection point metadata
447
448 The interface +javax.enterprise.inject.spi.InjectionPoint+ provides access to metadata about an injection point. An instance of +InjectionPoint+ may represent:
449
450 * an injected field or a parameter of a bean constructor, initializer method, producer method, disposer method or observer method, or
451 * an instance obtained dynamically using +Instance.get()+.
452
453
454 [source, java]
455 ----
456 public interface InjectionPoint {
457 public Type getType();
458 public Set<Annotation> getQualifiers();
459 public Bean<?> getBean();
460 public Member getMember();
461 public Annotated getAnnotated();
462 public boolean isDelegate();
463 public boolean isTransient();
464 }
465 ----
466
467 * The +getBean()+ method returns the +Bean+ object representing the bean that defines the injection point. If the injection point does not belong to a bean, +getBean()+ returns a null value. If the injection point represents a dynamically obtained instance, the +getBean()+ method should return the +Bean+ object representing the bean that defines the +Instance+ injection point.
468 * The +getType()+ and +getQualifiers()+ methods return the required type and required qualifiers of the injection point. If the injection point represents a dynamically obtained instance, the +getType()+ and +getQualifiers()+ methods should return the required type (as defined by +Instance.select()+), and required qualifiers of the injection point including any additional required qualifiers (as defined by +Instance.select()+).
469 * The +getMember()+ method returns the +Field+ object in the case of field injection, the +Method+ object in the case of method parameter injection, or the +Constructor+ object in the case of constructor parameter injection. If the injection point represents a dynamically obtained instance, the +getMember()+ method returns the +Field+ object representing the field that defines the +Instance+ injection point in the case of field injection, the +Method+ object representing the method that defines the +Instance+ injection point in the case of method parameter injection, or the +Constructor+ object representing the constructor that defines the +Instance+ injection point in the case of constructor parameter injection.
470 * The +getAnnotated()+ method returns an instance of +javax.enterprise.inject.spi.AnnotatedField+ or +javax.enterprise.inject.spi.AnnotatedParameter+, depending upon whether the injection point is an injected field or a constructor/method parameter. If the injection point represents a dynamically obtained instance, then the +getAnnotated()+ method returns an instance of +javax.enterprise.inject.spi.AnnotatedField+ or +javax.enterprise.inject.spi.AnnotatedParameter+ representing the +Instance+ injection point, depending upon whether the injection point is an injected field or a constructor/method parameter.
471 * The +isDelegate()+ method returns +true+ if the injection point is a decorator delegate injection point, and +false+ otherwise. If the injection point represents a dynamically obtained instance then +isDelegate()+ returns false.
472 * The +isTransient()+ method returns +true+ if the injection point is a transient field, and +false+ otherwise. If the injection point represents a dynamically obtained instance then the +isTransient()+ method returns +true+ if the +Instance+ injection point is a transient field, and +false+ otherwise.
473
474
475 Occasionally, a component with scope +@Dependent+ needs to access metadata relating to the object into which it is injected. For example, the following producer method creates injectable ++Logger++ s. The log category of a +Logger+ depends upon the class of the object into which it is injected:
476
477 [source, java]
478 ----
479 @Produces Logger createLogger(InjectionPoint injectionPoint) {
480 return Logger.getLogger( injectionPoint.getMember().getDeclaringClass().getName() );
481 }
482 ----
483
484 The container must provide a bean with scope +@Dependent+, bean type +InjectionPoint+ and qualifier +@Default+, allowing dependent objects, as defined in <<dependent_objects>>, to obtain information about the injection point to which they belong. The built-in implementation must be a passivation capable dependency, as defined in <<passivation_capable_dependency>>.
485
486 If a bean that declares any scope other than +@Dependent+ has an injection point of type +InjectionPoint+ and qualifier +@Default+, the container automatically detects the problem and treats it as a definition error.
487
488 If a disposer method has an injection point of type +InjectionPoint+ and qualifier +Default+, the container automatically detects the problem and treats it as a definition error.
489
490 If a Java EE component class supporting injection that is not a bean has an injection point of type +InjectionPoint+ and qualifier +@Default+, the container automatically detects the problem and treats it as a definition error.
491
492 [[bean_metadata]]
493
494 ==== Bean metadata
495
496 The interfaces +Bean+, +Interceptor+ and +Decorator+ provide metadata about a bean.
497
498 The container must provide beans allowing a bean instance to obtain a +Bean+, +Interceptor+ or +Decorator+ instance containing its metadata:
499
500 * a bean with scope +@Dependent+, qualifier +@Default+ and type +Bean+ which can be injected into any bean instance
501 * a bean with scope +@Dependent+, qualifier +@Default+ and type +Interceptor+ which can be injected into any interceptor instance
502 * a bean with scope +@Dependent+, qualifier +@Default+ and type +Decorator+ which can be injected into any decorator instance
503
504 Additionally, the container must provide beans allowing interceptors and decorators to obtain information about the beans they intercept and decorate:
505
506 * a bean with scope +@Dependent+, qualifier +@Intercepted+ and type +Bean+ which can be injected into any interceptor instance, and
507 * a bean with scope +@Dependent+, qualifier +@Decorated+ and type +Bean+ which can be injected into any decorator instance.
508
509
510 These beans are passivation capable dependencies, as defined in <<passivation_capable_dependency>>.
511
512 If an +Interceptor+ instance is injected into a bean instance other than an interceptor instance, the container automatically detects the problem and treats it as a definition error.
513
514 If a +Decorator+ instance is injected into a bean instance other than a decorator instance, the container automatically detects the problem and treats it as a definition error.
515
516 If a +Bean+ instance with qualifier +@Intercepted+ is injected into a bean instance other than an interceptor instance, the container automatically detects the problem and treats it as a definition error.
517
518 If a +Bean+ instance with qualifier +@Decorated+ is injected into a bean instance other than a decorator instance, the container automatically detects the problem and treats it as a definition error.
519
520 The injection of bean metadata is restricted. If:
521
522 * the injection point is a field, an initializer method parameter or a bean constructor, with qualifier +@Default+, then the type parameter of the injected +Bean+, +Interceptor+ or +Decorator+ must be the same as the type declaring the injection point, or
523 * the injection point is a field, an initializer method parameter or a bean constructor of an interceptor, with qualifier +@Intercepted+, then the type parameter of the injected +Bean+ must be an unbounded wildcard, or
524 * the injection point is a field, an initializer method parameter or a bean constructor of a decorator, with qualifier +@Decorated+, then the type parameter of the injected +Bean+ must be the same as the delegate type, or
525 * the injection point is a producer method parameter then the type parameter of the injected +Bean+ must be the same as the producer method return type, or
526 * the injection point is a parameter of a disposer method then the container automatically detects the problem and treats it as a definition error.
527
528 Otherwise, the container automatically detects the problem and treats it as a definition error.
529
530 [source, java]
531 ----
532 @Named("Order") public class OrderProcessor {
533
534 @Inject Bean<OrderProcessor> bean;
535
536 public void getBeanName() {
537 return bean.getName();
538 }
539
540 }
541 ----
542
543 [[programmatic_lookup]]
544
545 === Programmatic lookup
546
547 In certain situations, injection is not the most convenient way to obtain a contextual reference. For example, it may not be used when:
548
549 * the bean type or qualifiers vary dynamically at runtime, or
550 * depending upon the deployment, there may be no bean which satisfies the type and qualifiers, or
551 * we would like to iterate over all beans of a certain type.
552
553
554 In these situations, an instance of the +javax.enterprise.inject.Instance+ interface may be injected:
555
556 [source, java]
557 ----
558 @Inject Instance<PaymentProcessor> paymentProcessor;
559 ----
560
561 The method +get()+ returns a contextual reference:
562
563 [source, java]
564 ----
565 PaymentProcessor pp = paymentProcessor.get();
566 ----
567
568 Any combination of qualifiers may be specified at the injection point:
569
570 [source, java]
571 ----
572 @Inject @PayBy(CHEQUE) Instance<PaymentProcessor> chequePaymentProcessor;
573 ----
574
575 Or, the +@Any+ qualifier may be used, allowing the application to specify qualifiers dynamically:
576
577 [source, java]
578 ----
579 @Inject @Any Instance<PaymentProcessor> anyPaymentProcessor;
580 ...
581 Annotation qualifier = synchronously ? new SynchronousQualifier() : new AsynchronousQualifier();
582 PaymentProcessor pp = anyPaymentProcessor.select(qualifier).get().process(payment);
583
584 ----
585
586 In this example, the returned bean has qualifier +@Synchronous+ or +@Asynchronous+ depending upon the value of +synchronously+.
587
588 Finally, the +@New+ qualifier may be used, allowing the application to obtain a +@New+ qualified bean, as defined in <<new>>:
589
590 [source, java]
591 ----
592 @Inject @New(ChequePaymentProcessor.class) Instance<PaymentProcessor> chequePaymentProcessor;
593 ----
594
595 It's even possible to iterate over a set of beans:
596
597 [source, java]
598 ----
599 @Inject @Any Instance<PaymentProcessor> anyPaymentProcessor;
600 ...
601 for (PaymentProcessor pp: anyPaymentProcessor) pp.test();
602
603 ----
604
605 [[dynamic_lookup]]
606
607 ==== The +Instance+ interface
608
609 The +Instance+ interface provides a method for obtaining instances of beans with a specified combination of required type and qualifiers, and inherits the ability to iterate beans with that combination of required type and qualifiers from +java.lang.Iterable+:
610
611 [source, java]
612 ----
613 public interface Instance<T> extends Iterable<T>, Provider<T> {
614
615 public Instance<T> select(Annotation... qualifiers);
616 public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers);
617 public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers);
618
619 public boolean isUnsatisfied();
620 public boolean isAmbiguous();
621
622 public void destroy(T instance);
623
624 }
625 ----
626
627 For an injected +Instance+:
628
629 * the _required type_ is the type parameter specified at the injection point, and
630 * the _required qualifiers_ are the qualifiers specified at the injection point.
631
632
633 For example, this injected +Instance+ has required type +PaymentProcessor+ and required qualifier +@Any+:
634
635 [source, java]
636 ----
637 @Inject @Any Instance<PaymentProcessor> anyPaymentProcessor;
638 ----
639
640 The +select()+ method returns a child +Instance+ for a given required type and additional required qualifiers. If no required type is given, the required type is the same as the parent.
641
642 For example, this child +Instance+ has required type +AsynchronousPaymentProcessor+ and additional required qualifier +@Asynchronous+:
643
644 [source, java]
645 ----
646 Instance<AsynchronousPaymentProcessor> async = anyPaymentProcessor.select(
647 AsynchronousPaymentProcessor.class, new AsynchronousQualifier() );
648 ----
649
650 If an injection point of raw type +Instance+ is defined, the container automatically detects the problem and treats it as a definition error.
651
652 If two instances of the same qualifier type are passed to +select()+, an +IllegalArgumentException+ is thrown.
653
654 If an instance of an annotation that is not a qualifier type is passed to +select()+, an +IllegalArgumentException+ is thrown.
655
656 The +get()+ method must:
657
658 * Identify a bean that has the required type and required qualifiers and is eligible for injection into the class into which the parent +Instance+ was injected, according to the rules of typesafe resolution, as defined in <<performing_typesafe_resolution>>, resolving ambiguities according to <<unsatisfied_and_ambig_dependencies>>.
659 * If typesafe resolution results in an unsatisfied dependency, throw an +UnsatisfiedResolutionException+. If typesafe resolution results in an unresolvable ambiguous dependency, throw an +AmbiguousResolutionException+.
660 * Otherwise, obtain a contextual reference for the bean and the required type, as defined in <<contextual_reference>>.
661
662
663 The +iterator()+ method must:
664
665 * Identify the set of beans that have the required type and required qualifiers and are eligible for injection into the class into which the parent +Instance+ was injected, according to the rules of typesafe resolution, as defined in <<performing_typesafe_resolution>>, resolving ambiguities according to <<unsatisfied_and_ambig_dependencies>>.
666 * Return an +Iterator+, that iterates over the set of contextual references for the resulting beans and required type, as defined in <<contextual_reference>>.
667
668
669 The method +isUnsatisfied()+ returns +true+ if there is no bean that has the required type and qualifiers and is eligible for injection into the class into which the parent +Instance+ was injected, or +false+ otherwise.
670
671 The method +isAmbiguous()+ returns +true+ if there is more than one bean that has the required type and qualifiers and is eligible for injection into the class into which the parent +Instance+ was injected, or +false+ otherwise.
672
673 The method +destroy()+ instructs the container to destroy the instance. The bean instance passed to +destroy()+ should be a dependent scoped bean instance, or a client proxy for a normal scoped bean. Applications are encouraged to always call +destroy()+ when they no longer require an instance obtained from +Instance+. All built-in normal scoped contexts support destroying bean instances. An +UnsupportedOperationException+ is thrown if the active context object for the scope type of the bean does not support destroying bean instances.
674
675 [[builtin_instance]]
676
677 ==== The built-in +Instance+
678
679 The container must provide a built-in bean with:
680
681 * +Instance<X>+ and +Provider<X>+ for every legal bean type +X+ in its set of bean types,
682 * every qualifier type in its set of qualifier types,
683 * scope +@Dependent+,
684 * no bean name, and
685 * an implementation provided automatically by the container.
686
687
688 The built-in implementation must be a passivation capable dependency, as defined in <<passivation_capable_dependency>>.
689
690 [[annotationliteral_typeliteral]]
691
692 ==== Using +AnnotationLiteral+ and +TypeLiteral+
693
694 +javax.enterprise.util.AnnotationLiteral+ makes it easier to specify qualifiers when calling +select()+:
695
696 [source, java]
697 ----
698 public PaymentProcessor getSynchronousPaymentProcessor(PaymentMethod paymentMethod) {
699
700 class SynchronousQualifier extends AnnotationLiteral<Synchronous>
701 implements Synchronous {}
702
703 class PayByQualifier extends AnnotationLiteral<PayBy>
704 implements PayBy {
705 public PaymentMethod value() { return paymentMethod; }
706 }
707
708 return anyPaymentProcessor.select(new SynchronousQualifier(), new PayByQualifier()).get();
709 }
710 ----
711
712 +javax.enterprise.util.TypeLiteral+ makes it easier to specify a parameterized type with actual type parameters when calling +select()+:
713
714 [source, java]
715 ----
716 public PaymentProcessor<Cheque> getChequePaymentProcessor() {
717 PaymentProcessor<Cheque> pp = anyPaymentProcessor
718 .select( new TypeLiteral<PaymentProcessor<Cheque>>() {} ).get();
719 }
720 ----
721