Over a million developers have joined DZone.
Gold Partner

Working with multiple CDI qualifiers

· Java Zone

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

An injection point may specify multiple qualifiers. When you specify multiple qualifiers, only the beans that annotated with those qualifiers will be injected - a bean can have multiple qualifiers and injection points only need to specify enough qualifiers to uniquely match a bean. Per example, let us suppose that you have the below two qualifiers – each qualifier represent a tennis player:

package com.racquets;

//imports here

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

package com.racquets;

//imports here

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

Both top players, Rafael Nadal and Jo-Wilfred Tonga play with the same racquet, a Babolat AeroPro Drive GT. Therefore, a possible implementation of RacquetType type can be annotated with both qualifiers from above:
package com.racquets;

@RafaelNadal @JoWilfriedTsonga
public class AeroProDriveGTRacquet implements RacquetType {

@Override
public String getRacquetType() {
return ("Babolat AeroPro Drive GT");
}
}


Now, at the injection point you must specify both qualifiers, like below:
package com.racquets;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@RequestScoped
@Named
public class AeroProDriveGTBean {

@Inject @RafaelNadal @JoWilfriedTsonga RacquetType aeroprodrivegtRacquet;
private String aeroprodrivegtRacquetName;

public String getAeroprodrivegtRacquetName() {
aeroprodrivegtRacquetName = aeroprodrivegtRacquet.getRacquetType();
return aeroprodrivegtRacquetName;
}
}


From a JSF page, you can test multiple qualifiers like this:
<br/><h3><b>Multiple qualifiers</b></h3>        
<b>Rafael Nadal and Jo-Wilfried Tsonga racquet:</b>
<h:outputText value="#{aeroProDriveGTBean.aeroprodrivegtRacquetName}" /><br/>


The output is in figure below:

 

From http://e-blog-java.blogspot.com/2011/04/working-with-multiple-cdi-qualifiers.html

The Java Zone is brought to you in partnership with Azul Systems.   Discover how to stop tuning and get back to coding with Azul Zing.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}