您的位置:首页 > 编程语言 > Java开发

Spring注解@Qualifier用法

2018-02-06 11:44 519 查看
在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注解的名称之一!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring 注解