Java Reference
In-Depth Information
@Produces
@Chosen
@RequestScoped
public Coder getCoder(@New TestCoderImpl tci,
@New CoderImpl ci) {
switch (coderType) {
case TEST:
return tci;
case SHIFT:
return ci;
default:
return null;
}
}
The
javax.enterprise.inject.New
qualifier instructs the CDI runtime to instan-
tiate both of the coder implementations and provide them as arguments to the producer
method. Here,
getCoder
becomes in effect a getter method, and when the
coder
prop-
erty is injected with the same qualifier and other annotations as the method, the selected
version of the interface is used.
@Inject
@Chosen
@RequestScoped
Coder coder;
Specifying the qualifier is essential: It tells CDI which
Coder
to inject. Without it, the
CDI implementation would not be able to choose between
CoderImpl
,
TestCoder-
Impl
, and the one returned by
getCoder
, and would cancel deployment, informing the
user of the ambiguous dependency.
Using Producer Fields to Generate Resources
A common use of a producer field is to generate an object such as a JDBC
DataSource
or a Java Persistence API
EntityManager
. The object can then be managed by the
container. For example, you could create a
@UserDatabase
qualifier and then declare
a producer field for an entity manager as follows:
@Produces
@UserDatabase