gpt4 book ai didi

java - 使用具有多个实现的接口(interface)的 Spring 依赖注入(inject)

转载 作者:行者123 更新时间:2023-11-29 09:03:43 25 4
gpt4 key购买 nike

我的问题已在以下链接中提出。

Spring: Why do we autowire the interface and not the implemented class?

如果我们使用 @Qualifier 注入(inject) bean,我想知道的是什么,而不是 Autowiring 接口(interface)的目的是什么?为什么我们不自动连接相同的实现类??

通过 Autowiring 接口(interface),我们希望利用运行时多态性,但如果我们遵循 @Qualifier 的方法,则无法实现。请给我一个标准的方法。

如果没有 Spring ,下面是简单的代码。我想知道 spring 将如何注入(inject) 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;
}

}

最佳答案

除了 mthmulders 所说的,以下场景也适用 -

当只有一个实现时,按类型 Autowiring 工作。如果您有多个实现,那么 Spring 需要知道选择哪一个。 @Qualifier 允许您定义在这种情况下选择哪一个。

关于java - 使用具有多个实现的接口(interface)的 Spring 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com