Spring @Qualifier 注解,一个service 接口,有多个实现时,如何在controller 只引入service 接口,进而实现引入具体bean

参考: https://blog.csdn.net/mazuyu408/article/details/79629846

@Qualifier 作用

在只引入service 接口的情况下在,指示spring 引入value 为那个别名的具体service 实现类

场景:

假设有一个场景,一个service 接口定义了多个 实现类,而在controller 我只想引入 service 接口,而这时,因为有个实现spring 不知道具体引入那个就会报错

接口;

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

实现1:起别名,标记为service

@Service("service")
public class EmployeeServiceImpl implements EmployeeService {
    public EmployeeDto getEmployeeById(Long id) {
        return new EmployeeDto();
    }
}

实现2:起别名,标记为service1

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

产生的问题:

这样引入时的报错信息:提示 创建Bean EmployeeInfoControl失败,由于@autowired  employeeService失败,

没有类型[com.test.service]的唯一bean。定义:期望的单个匹配bean,但发现2:[service1, service2]

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]

 解决办法:

前面我们不是分别给两个service实现类起了别名吗,这里实际要导入那个类型,(假设要导入的是,EmployeeServiceImpl 别名是service,可以将controller 修改如下

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

或者使用@Resource 注解

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

 

你可能感兴趣的:(java,spring)