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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}