Kwalifikator i alternatywa

Kwalifikator umożliwia jednoznaczne wskazanie komponentu (konkretnej implementacji), który ma zostać wstrzyknięty. Na przykład poniższy kod deklaruje nowy kwalifikator @Fancy:

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

Poniższy fragment kodu definiuje nową implementację interfejsu Greeting:

@Fancy
public class FancyGreeting implements Greeting {
    public String greet(String name) {
        return "Miło się widzieć, witaj " + name;
    }
}

i wstrzykuje ją do klasy GreetingService za pomocą adnotacji @Fancy użytej w roli kwalifikatora:

@Stateless public class GreetingService { @Inject @Fancy Greeting greeting; public String sayHello(String name) { return greeting.greet(name); ...

Get Java EE 6. Leksykon kieszonkowy now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.