Spring的注解@Qualifier小結
近期在捯飭spring的注解,現將遇到的問題記錄下來,以供遇到同樣問題的童鞋解決~
先說明下場景,代碼如下
有如下接口:
1
2
3
|
public interface EmployeeService { public EmployeeDto getEmployeeById(Long id); } |
同時有下述兩個實現類 EmployeeServiceImpl和EmployeeServiceImpl1:
1
2
3
4
5
6
7
8
9
10
11
12
|
@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(); } } |
調用代碼如下:
1
2
3
4
5
6
7
8
9
10
|
@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注解的名稱之一!
1
2
3
4
5
6
7
8
9
10
11
|
@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) { #略 } } |
問題解決!
@qualifier注解
@Qualifier限定哪個bean應該被自動注入。當Spring無法判斷出哪個bean應該被注入時,@Qualifier注解有助于消除歧義bean的自動注入。
參見下面的例子
1
2
3
4
|
public class Staff{ @Autowired private user user; } |
我們有兩個bean定義為Person類的實例。
1
2
3
4
5
|
< beanid = "staff" class = "com.test.Staff" /> < beanid = "user1" class = "com.test.User" > < property name = "name" value = "zhangsan" /></ bean > < beanid = "user2" class = "com.test.User" > < property name = "name" value = "lisi" /></ bean > |
Spring 知道哪個bean應該自動注入?不。當您運行上面的例子時,拋出如下異常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.test.User] is defined: expected single matching bean but found2: [user1, user2]
要解決以上問題,你需要使用@Quanlifier注解告訴Spring 哪個bean應該被autowired的。
1
2
3
4
5
6
|
public class Staff { @Autowired @Qualifier ( "user1" ) private User user; } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/smileLuckBoy/p/5801678.html