Java Reference
In-Depth Information
Producer methods and JPA
You might be wondering how CDI performs all of its magic. To provide these features, CDI
wraps your bean in a proxy object. If you perform an instanceof on a bean that has
been injected, comparing it against its type, it will return true. Most of the time, the fact
that the injected bean is a proxy object isn't an issue. But JPA implementations often do
care. If you try to pass a bean instance created by CDI to JPA, JPA will claim that the bean
can't be persisted and that it isn't a known type. To solve this problem, you'll need to use a
producer method and keep a reference to the original POJO. Anyone who gets a reference
via injection will be working with a proxy.
In any bean in the application, you can now use the following code to get a reference to the
current user:
@Inject
private User currentUser;
When looking at this code, remember to focus on the type. The name of the field is irrel-
evant as far as CDI is concerned. CDI does injection based on the type, which is there-
fore type-safe injection. But you may want to inject different instances of the User ob-
ject—perhaps the User object is someone a customer service representative is currently
servicing. In the next section you'll see how you can use qualifiers to add an additional
layer of specificity beyond just the type of the injection point.
12.3.3. Using qualifiers
Dependency injection using just the type information is very powerful, but at this point you
might be wondering whether you're limited to one instance of a given type. In the case of
the current user example in the last section, what if you wanted to inject another instance
representing the user a customer service representative is helping? CDI has a solution for
this problem called a qualifier . A qualifier enables you to qualify certain injection points
as using different instances of a bean. It enables you to mark a User object as being either
the current user or the current user being helped and so on. A qualifier is specified using a
custom annotation.
Search WWH ::




Custom Search