近期在捯飭spring的註解,現將遇到的問題記錄下來,以供遇到同樣問題的童鞋解決~
先說明下場景,程式碼如下:
有如下介面:
public interface EmployeeService { public EmployeeDto getEmployeeById(Long id); }
同時有下述兩個實現類 EmployeeServiceImpl和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(); } }
呼叫程式碼如下:
@Controller @RequestMapping("/emplayee.do") public class EmployeeInfoControl { @Autowired EmployeeService employeeService; @RequestMapping(params = "method=showEmplayeeInfo") public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) { #略 } }
在啟動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]
其實報錯資訊已經說得很明確了,在autoware時,由於有兩個類實現了EmployeeService介面,所以Spring不知道應該繫結哪個實現類,所以丟擲瞭如上錯誤。
這個時候就要用到@Qualifier註解了,qualifier的意思是合格者,通過這個標示,表明了哪個實現類才是我們所需要的,我們修改呼叫程式碼,新增@Qualifier註解,需要注意的是@Qualifier的引數名稱必須為我們之前定義@Service註解的名稱之一!
@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) { #略 } }
問題解決!