Nov 8, 2018

How to use Qualifiers in Java EE

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 @I88Ca qualifier type and apply it to another class. To declare this qualifier type, you would use the following code:
package ca.i88.example;

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 java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface I88Ca {}

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


package ca.i88.example;

@I88Ca
public class I88CaClass extends MyDefaultClass {
    //...
}

Now both implementations of the bean ( I88CaClass and MyDefaultClass ) can be used in the application.

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


package ca.i88.example;

import javax.enterprise.inject.Default;

@Default
public class MyDefaultClass {
    //...
}