My question has already been asked here in the following link.
Spring: Why do we autowire the interface and not the implemented class?
What I want to know if we use @Qualifier
to inject a bean than what is the purpose of autowiring an interface ?? Why not we auto-wire the same implementation class ??
By autowiring an interface we want to take advantage of run-time polymorphism but that's not achieved if we follow the approach of @Qualifier
. Please suggest me a standard way.
Following is the simple code if I do it without spring. I wonder how spring will inject the PrepaidPaymentService instance and PostPaidPaymentService instance??
public interface PaymentService{
public void processPayment();
}
public class PrepaidPaymentService implements PaymentService{
public void processPayment(){
System.out.println("Its Prepaid Payment Service");
}
}
public class PostPaidPaymentService implements PaymentService{
public void processPayment(){
System.out.println("Its Postpaid Payment Service");
}
}
public class Test {
public PaymentService service;
public static void main(String[] args) {
Test test = new Test();
int i = 1;
if(i ==1 ){
test.setService(new PrepaidPaymentService());
test.service.processPayment();
}
i = 2;
if(i == 2){
test.setService(new PostPaidPaymentService());
test.service.processPayment();
}
}
public void setService(PaymentService service){
this.service = service;
}
}