码迷,mamicode.com
首页 > 编程语言 > 详细

Spring的注解@Qualifier小结

时间:2018-06-07 11:42:30      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:div   fine   employee   cep   matching   定义   control   cti   show   

说明下场景,代码如下:

有如下接口:

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

 

 

转载自:https://www.cnblogs.com/smileLuckBoy/p/5801678.html

Spring的注解@Qualifier小结

标签:div   fine   employee   cep   matching   定义   control   cti   show   

原文地址:https://www.cnblogs.com/PengChengLi/p/9149413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!