Spring的註解@Qualifier小結

  近期在捯飭spring的註解,現將遇到的問題記錄下來,以供遇到一樣問題的童鞋解決~spring

  先說明下場景,代碼以下:tomcat

有以下接口:app

public interface EmployeeService {
    public EmployeeDto getEmployeeById(Long id);
}

 

同時有下述兩個實現類 EmployeeServiceImpl和EmployeeServiceImpl1:spa

@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();
    }
}

 

調用代碼以下:code

@Controller
@RequestMapping("/emplayee.do")
public class EmployeeInfoControl {
    
    @Autowired
    EmployeeService employeeService;
     
    @RequestMapping(params = "method=showEmplayeeInfo")
    public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) {
        #略
    }
}

 

 

  在啓動tomcat時報以下錯誤:blog

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註解的名稱之一!ci

@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) {
        #略
    }
}

 

 問題解決!get

相關文章
相關標籤/搜索