Spring注解@Qualifier用法

在Spring中有注解@AutoWired可以写在接口的声明上,然后就可以用此声明调用接口的方法,大家都知道是此过程是Srping将接口的实现类依赖注入给了接口的声明,大多数情况下接口的实现类是只有一个,如果有多个实现类怎么办,这时就用到我们接下来要讲的这个注解了

刚才说了@Qualifier是用于接口有多个实现类的时候,那么有一个接口

          public interface A{

           //A do something 

同时有下述两个实现类B和C:

@Service("B")
public class B implements A { //B重写A的方法
//B重写A的方法
}
@Service("C")
public class C implements A {
C重写A的方法
}
@Controller
@RequestMapping("/user")
public class EmployeeInfoControl { @Autowired
@Autowired
A a;
@RequestMapping(params = "method=showEmplayeeInfo")
public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) { #略 }}
#略
}
}
在启动tomcat时报如下错误:
@Controller
@RequestMapping("/user")
public class EmployeeInfoControl { @Autowired @Qualifier(
@Autowired
@Qualifier("B") A a; @RequestMapping(params
A a;
@RequestMapping(params = "method=showEmplayeeInfo")
public void showEmplayeeInfo(HttpServletRequest request, HttpServletResponse response, EmployeeDto dto) { #略 }}
#略
}
}

调用代码如下

 

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时,由于有两个类实现了A接口,所以Spring不知道应该绑定哪个实现类,所以抛出了如上错误。

这个时候就要用到@Qualifier注解了 ,通过这个标示,表明了哪个实现类才是我们所需要的,我们修改调用代码,添加@Qualifier注解,需要注意的是@Qualifier的参数名称必须为我们之前定义@Service注解的名称之一!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值