我的问题已经在以下链接中提出。
我想知道我们是否使用@Qualifier
注入 bean 而不是自动装配接口的目的是什么?为什么我们不自动连接相同的实现类?
通过自动装配接口,我们希望利用运行时多态性,但如果我们遵循@Qualifier
. 请给我一个标准的方法。
如果我在没有弹簧的情况下这样做,以下是简单的代码。我想知道 spring 将如何注入 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;
}
}