我的問題已經在下面的鏈接中提到。Spring使用多個實現接口的依賴注入
Spring: Why do we autowire the interface and not the implemented class?
我想知道,如果我們使用@Qualifier
注入一個bean比什麼是自動裝配接口的目的是什麼?我們爲什麼不自動連線相同的實現類?
通過自動裝配接口,我們希望利用運行時多態性,但如果我們遵循@Qualifier
的方法,則無法實現這一點。請給我一個標準的方法。
以下是簡單的代碼,如果我沒有彈簧。我不知道春天將如何注入PrepaidPaymentService實例和PostPaidPaymentService實例?
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;
}
}
決定實現類的條件是什麼? – shazinltc