Java Reference
In-Depth Information
LISTING 5‐7: (continued)
private UserDataRepository udr;
public void persistUser(User user) {;
The CDI container constructs a single UserDataRepositoryImpl instance as a container managed
bean and injects it anywhere it i nds @Inject annotating a i eld of type UserDataRepository .
You can inject a container‐managed bean into constructors, methods, and i elds, regardless of the
access modii er, although i elds must not be i nal, and the method must not be abstract.
Some important questions arise. What happens if there is more than one implementation of the
UserDataRepository interface? How does the CDI container identify the correct implementation
to inject? To disambiguate the concrete implementations of the UserDataRepository interface, you
can annotate the concrete class using a developer‐dei ned qualii er.
Imagine having two implementations of the UserDataRepository interface: one for a Mongo DB
collection (a document based database) and another for a MySQL database (relational database).
You would have to create two qualii ers (one for the Mongo implementation and another for the
MySQL implementation), the concrete class would be annotated at the class level with the relevant
qualii er, and in the class in which the UserDataRepository is to be injected, a i eld would be
annotated with the same qualii er.
If you refactor the UserService class in Listing 5‐7 to use the Mongo implementation of the
UserDataRepository , you would add
@Mongo to the udr i eld as follows:
@Inject @Mongo
private UserDataRepository udr;
The use of qualii ers is discussed in more depth below and in Chapter 6.
The @Named Annotation
Another great achievement was the introduction of the @Named annotation instead of String
qualii ers. Ambiguities in EJB dependencies were resolved by using a String in the beanName
attribute of the @EJB annotation that specii ed the implementation to be injected:
@EJB(beanName="UserDataRepository") . The @Name annotation also supports disambiguation
with the use of a String attribute. In Listing 5‐8, the Mongo implementation of the
UserDataRepository is injected into the udr i eld.
LISTING 5‐8: The @Named annotation used to disambiguate
package com.devchronicale.di;
import javax.inject.Inject;
Search WWH ::

Custom Search