Skip to main content
IoC and dependency injection · Topic 4 of 7

Qualifier and Primary

Definition​

When two beans implement the same interface, Spring does not know which to inject and fails. @Primary marks the default one. @Qualifier("name") picks a specific one at the injection point.

Example code​

Two notifiers: one default, one chosen by name

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

interface Notifier { String send(String text); }

@Component
@Primary // the default choice
class EmailNotifier implements Notifier {
public String send(String text) { return "email: " + text; }
}

@Component("sms")
class SmsNotifier implements Notifier {
public String send(String text) { return "sms: " + text; }
}

@Component
class Alerts {
private final Notifier normal;
private final Notifier urgent;

Alerts(Notifier normal, @Qualifier("sms") Notifier urgent) { // default, and a named one
this.normal = normal;
this.urgent = urgent;
}

void run() {
System.out.println(normal.send("report ready"));
System.out.println(urgent.send("server down"));
}
}

@ComponentScan
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
context.getBean(Alerts.class).run();
}
}
}

// Output:
// email: report ready
// sms: server down

Finished this page? Track your progress (saved only in your browser).