【发布时间】:2013-04-11 05:39:05
【问题描述】:
我的问题已在以下链接中提出。
Spring: Why do we autowire the interface and not the implemented class?
我想知道如果我们使用@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;
}
}
【问题讨论】:
-
什么条件决定了实现类?
标签: java spring jakarta-ee autowired