Java Reference
In-Depth Information
To define a qualifier, you define a new annotation and annotate the annotation with @Qu-
alifier . The reason you're defining a new annotation and annotating, as opposed to
passing a string name to a qualifier annotation, is so that you have strong typing. This is
one of the differentiating features of CDI and reduces errors at runtime. The new annota-
tion is then placed on both the injection points and the producer methods.
Building on the example of injecting the current authenticated user, you'll define a qualifier
for the current authenticated user. This improves the readability of the code and also
enables you to inject other user instances. The following code snippet defines the
@AuthenticatedUser and @Seller qualifiers:
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface AuthenticatedUser {}
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Seller {}
After defining the qualifier, you need to add the qualifier to the producer method:
@Produces @SessionScoped @AuthenticatedUser @Named("currentUser")
public User getCurrentUser() {
...
}
Once the qualifier has been defined, you can use it to tell CDI which instance you want
injected, as shown in the next listing.
Search WWH ::




Custom Search