3

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;
    }

}
Community
  • 1
  • 1
Jawad
  • 408
  • 4
  • 11

2 Answers2

0

One reason is that by autowiring the interface (even with a @Qualifier) you can inject a different implementation for testing purposes.

For example, if you have a service that uses a DAO to access a database, you might want to replace that DAO in order to unit-test the service.

mthmulders
  • 9,483
  • 4
  • 37
  • 54
0

Apart from what mthmulders said following scenario is also applicable -

Autowiring by type works when only one implementation is present. If you have multiple implementations present then Spring needs to know which one to pick. @Qualifier allows you to define which one to pick in this scenario.

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
  • Yes that is my point where I am getting confused. I have to specify by my own which implementation to pick by using @Qualifier and then recompile my code . what i should do to make the container understand at runtime that if it is 'case 1' give me the instance of 'ImplementationOne' else give me the instance of 'ImplementationTwo'. – Jawad Apr 18 '13 at 08:23
  • At runtime from where the information will be provided that you are interested in ImplementationOne or ImplementationTwo? – Bhushan Bhangale Apr 18 '13 at 08:24