【问题标题】:Spring Dependency injection using interface with more than one implementation使用具有多个实现的接口的 Spring 依赖注入
【发布时间】: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


【解决方案1】:

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

当只有一个实现存在时,按类型自动装配有效。如果你有多个实现,那么 Spring 需要知道选择哪一个。 @Qualifier 允许您定义在这种情况下选择哪一个。

【讨论】:

  • 是的,这就是我感到困惑的地方。我必须自己指定使用 @Qualifier 选择哪个实现,然后重新编译我的代码。我应该怎么做才能让容器在运行时理解如果是“案例 1”,则给我“ImplementationOne”的实例,否则给我“ImplementationTwo”的实例。
  • 在运行时从哪里提供您对 ImplementationOne 或 ImplementationTwo 感兴趣的信息?
【解决方案2】:

一个原因是通过自动装配接口(即使使用@Qualifier),您可以注入不同的实现以进行测试。

例如,如果您有一个使用 DAO 访问数据库的服务,您可能需要替换该 DAO 以便对该服务进行单元测试。

【讨论】:

  • 这个答案像现在的电影一样有一个开放式结局;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2014-10-06
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
相关资源
最近更新 更多