Spring注解之@Qualifier
程序员文章站
2022-05-24 14:35:03
...
@Qualifier:限定描述符,用于细粒度选择候选者;
@Autowired默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,则需要限定其中一个候选者,否则将抛出异常
场景如下:
现有有接口:
public interface EmployeeService {
public EmployeeDto getEmployeeById(Long id);
}
同时有下述两个实现类 EmployeeServiceImpl和EmployeeServiceImplOne:
@Service("service")
public class EmployeeServiceImpl implements EmployeeService {
public EmployeeDto getEmployeeById(Long id) {
return new EmployeeDto();
}
}
@Service("serviceOne")
public class EmployeeServiceImplOne 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]
其实报错信息已经说得很清楚了,在@autowired时,由于有两个类实现了EmployeeService接口,所以Spring不知道应该具体绑定那个实现类,所以抛出了如上错误。
这个时候就该用到@Qualifier注解了,被@Qualifier标注的意为合格者,通过标识才知道那个是我们所需要的,我们修改调用代码,添加@Qualifier注解:
@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) {
... ...
}
}
上一篇: PHP上傳實例
下一篇: Servlet实现文件下载