Java Reference
In-Depth Information
12.3.2. Producer methods
In the last section you saw how you could use dependency injection with constructors to
create a more natural approach to instantiating beans that was akin to how POJOs are con-
structed and used. But there are many situations where you need total control over the in-
stantiation of a bean. For example, the bean instance might be derived from a record in a
database or require some custom logic that prepares the bean instance or chooses the type
that will be instantiated. To accommodate this requirement, CDI has the concept of a pro-
ducer method . A producer is a method or instance variable that's consulted by CDI to create
a bean instance. The method or instance variable is marked with the @Producer annota-
tion. Because CDI is type-safe, it'll use the instance or return type to determine what type
of bean the producer creates. A producer can also be annotated with a qualifier, but we'll
defer discussion of qualifiers to later in the chapter. To better understand producers, let's
look at an example from the ActionBazaar application in the following listing.
Listing 12.6. Producer providing a "currentUser" user instance
Search WWH ::




Custom Search