Java annotation Qualifier

There are the following interfaces:

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

At the same time, there are the following two implementation classes EmployeeServiceImpl and EmployeeServiceImpl1:

copy code

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

copy code

 

The calling code is as follows:

copy code

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

copy code

 

 

  The following error occurs when starting tomcat:

copy code

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]

copy code

  In fact, the error message has been clearly stated. In autoware, since there are two classes that implement the EmployeeService interface, Spring does not know which implementation class should be bound, so the above error is thrown.

At this time, we need to use the @Qualifier annotation. Qualifier means a qualified person. Through this mark, it indicates which implementation class is what we need. We modify the calling code and add the @Qualifier annotation. Note that @Qualifier The parameter name must be one of the names of the @Service annotation we defined earlier!

copy code

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325992925&siteId=291194637