Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking.I'm 23, born in Romania, student at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff. I know that I look and act differently from most developers, but this is why you will love to work with me! Constantin has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

Working with multiple CDI qualifiers

04.22.2011
| 4472 views |
  • submit to reddit

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

Published at DZone with permission of its author, Constantin Alin.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: