
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:
No comments:
Post a Comment