Java 註解 Qualifier

有以下接口:spring

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

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

複製代碼

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

複製代碼

 

調用代碼以下:app

複製代碼

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

複製代碼

 

 

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

複製代碼

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) {
        #略
    }
}
相關文章
相關標籤/搜索