There are the following interfaces:
public interface EmployeeService { public EmployeeDto getEmployeeById(Long id); }
At the same time, there are the following two implementation classes EmployeeServiceImpl and EmployeeServiceImpl1:
@Service("service") public class EmployeeServiceImpl implements EmployeeService { public EmployeeDto getEmployeeById(Long id) { return new EmployeeDto(); } } @Service("service1") public class EmployeeServiceImpl1 implements EmployeeService { public EmployeeDto getEmployeeById(Long id) { return new EmployeeDto(); } }
The calling code is as follows:
@Controller @RequestMapping("/emplayee.do") public class EmployeeInfoControl { @Autowired EmployeeService employeeService; @RequestMapping(params = "method=showEmplayeeInfo") public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) { #slightly } }
The following error occurs when starting tomcat:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeInfoControl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.test.service.EmployeeService com.test.controller.EmployeeInfoControl.employeeService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.test.service.EmployeeService] is defined: expected single matching bean but found 2: [service1, service2]
In fact, the error message has been clearly stated. In autoware, since there are two classes that implement the EmployeeService interface, Spring does not know which implementation class should be bound, so the above error is thrown.
At this time, we need to use the @Qualifier annotation. Qualifier means a qualified person. Through this mark, it indicates which implementation class is what we need. We modify the calling code and add the @Qualifier annotation. Note that @Qualifier The parameter name must be one of the names of the @Service annotation we defined earlier!
@Controller @RequestMapping("/emplayee.do") public class EmployeeInfoControl { @Autowired @Qualifier("service") EmployeeService employeeService; @RequestMapping(params = "method=showEmplayeeInfo") public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) { #slightly } }