| Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial |
| Previous | Next | Contents |
You can use qualifiers to provide various implementations of aparticular bean type. A qualifier is an annotation that you apply to abean. 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 applyit to another class that extends theGreeting class. To declare thisqualifier type, 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 theGreeting class anduses this qualifier:
package greetings;@Informalpublic 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, then the bean automatically has thequalifier@Default. The unannotatedGreeting class could be declaredas follows:
package greetings;import javax.enterprise.inject.Default;@Defaultpublic class Greeting { public String greet(String name) { return "Hello, " + name + "."; }}| Previous | Next | Contents |
Copyright © 2017, Oracle and/or its affiliates. All rights reserved.