karunakar reddy
karunakar reddy

Reputation: 1

spring dependency interface injection with two implemented classes

consider a scenario of interface injection in spring, I have an interface which was implemented by two class. If we inject the Interface in another class using @Autowired. Now if we call a method in that interface then which class implemented method will be called? consider that we are not using @Qualifier annotation.

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
       }
}

now we inject EmployeeDAOI to some class

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 ?
}

Upvotes: 0

Views: 386

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

None. You get an exception:

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

Spring expects exactly one instance, unless the injection is done for a Collection of those instances or you use a way of differentiating (@Qualifier).

Upvotes: 1

Related Questions