Spring Qualifier

What if we had more than one implementation of the intere, we need to use the @Qualifier annotation

Eg: If we had EmailService and SMSService registered as a bean

public interface MessageService {

    void sendMessage(String recipient, String content);

}
@Service
public class EmailService implements MessageService {

    @Override
    public void sendMessage(String recipient, String content) {
        //Create EmailService using JavaMail..etc
    }

}

@Service 
public class SMSService implements MessageService {

    @Override
    public void sendMessage(String recipient, String content) {
        //Create SMSService using Whispir SMS Gateway..etc
    }

}

Using the @Qualifier

@Service
public class TodoService {

    private final MessageService smsService;

    private final MessageService emailService;

    @Autowired
    public TodoService(@Qualifier("smsService") MessageService smsService,
                       @Qualifier("emailService") MessageService emailService) {
        this.smsService= smsService;
        this.messageService = messageService;
    }

}
  • The @Qualifier takes in a string name, which is the class name starting with a lowercase

results matching ""

    No results matching ""