【问题标题】:spring dependency interface injection with two implemented classes带有两个实现类的spring依赖接口注入
【发布时间】:2014-08-08 19:32:33
【问题描述】:

考虑一个spring中的接口注入场景,我有一个由两个类实现的接口。如果我们使用@Autowired 在另一个类中注入接口。现在,如果我们在该接口中调用一个方法,那么将调用哪个类实现的方法?考虑到我们没有使用@Qualifier 注解。

enter code here

public interface EmployeeDAOI{
 void save();
  }


public class Emp1 implements EmployeeDAOI{
  public void save(){ 
        //some logic
   }
}

public class Emp2 implements EmployeeDAOI{
 public void save(){
      //some logic
       }
}

现在我们将 EmployeeDAOI 注入到某个类中

public class IterfaceEx{
@Autowired
private EmployeeDAOI edaoi;
public void setEmployeeDAOI(EmployeeDAOI edaoi){
 this.edaoi=edaoi;
 }

edaoi.save();  // My question is here which class method will be called ?
}

【问题讨论】:

    标签: spring dependency-injection


    【解决方案1】:

    没有。 你得到一个例外:

     org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [EmployeeDAOI] is defined: expected single matching bean but found 2: [emp1 , emp2]
    

    Spring 只需要一个实例,除非注入是针对这些实例中的 Collection 完成的,或者您使用了一种区分方式 (@Qualifier)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      相关资源
      最近更新 更多