基於Spring的註解@Qualifier小結

Spring的註解@Qualifier小結

近期在捯飭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) {
        #略
    }
}

問題解決!

@qualifier註解

@Qualifier限定哪個bean應該被自動註入。當Spring無法判斷出哪個bean應該被註入時,@Qualifier註解有助於消除歧義bean的自動註入。

參見下面的例子

public class Staff{    
    @Autowired    
    private user user;
}

我們有兩個bean定義為Person類的實例。

<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的。

public class Staff
{
    @Autowired
    @Qualifier("user1")
    private User user;
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: