Suppose my interface extends CrudRepository as follows
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>
{
}
and I use the EmployeeRepository interface in my Service class as follows
@Service
public class EmployeeService
{
@Autowired
EmployeeRepository employeeRepository;
public List<Employee> getAllEmployee()
{
List<Employee> listEmp=new ArrayList<Employee>();
employeeRepository.findAll().forEach(listEmp::add);
return listEmp;
}
}
and controller as follows
@RestController
public class WelcomeController
{
@Autowired
EmployeeService empservice;
@RequestMapping("/employees")
public List<Employee> getEmployees()
{
return empservice.getAllEmployee();
}
}
and it gives the following exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'welcomeController': Unsatisfied dependency expressed through field 'empservice': Error creating bean with name 'employeeService': Unsatisfied dependency expressed through field 'employeeRepository'
The error is obvious because interface EmployeeRepository is not implemented by any class and
@Autowired
EmployeeRepository employeeRepository;
Autowired will fail because no class is implementing employeeRepository.
Still, I am confused as to how it works as, every code I saw on GitHub and tutorial, works perfectly.
Where am I going wrong and how does @Autowired work on the interface which extends CrudRepository, even though no class is implementing it; which is the basic rule of Autowiring? That is, if you are auto wiring any interface, at least one class has to implement that interface then and then Autowiring will be successful.