Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Working with multiple CDI qualifiers

DZone's Guide to

Working with multiple CDI qualifiers

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}