Documentation



Send Feedback | Print | PDF | ePub | Mobi
Java Platform, Enterprise Edition: The Java EE Tutorial

23.6 Using Qualifiers

You can use qualifiers to provide various implementations of a particular bean type. A qualifier is an annotation that you apply to a bean. A qualifier type is a Java annotation defined as @Target({METHOD, FIELD, PARAMETER, TYPE}) and @Retention(RUNTIME).

For example, you could declare an @Informal qualifier type and apply it to another class that extends the Greeting class. To declare this qualifier type, you would use the following code:

package greetings;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Informal {}

You can then define a bean class that extends the Greeting class and uses this qualifier:

package greetings;
@Informal
public class InformalGreeting extends Greeting {
 public String greet(String name) {
 return "Hi, " + name + "!";
 }
}

Both implementations of the bean can now be used in the application.

If you define a bean with no qualifier, the bean automatically has the qualifier @Default. The unannotated Greeting class could be declared as follows:

package greetings;
import javax.enterprise.inject.Default;
@Default
public class Greeting {
 public String greet(String name) {
 return "Hello, " + name + ".";
 }
}

Table of Contents

Java Platform, Enterprise Edition: The Java EE Tutorial

|

Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Legal Notices

AltStyle によって変換されたページ (->オリジナル) /