1、@Qualifier

出现场景:

老项目中有多个实现类实现同一个接口时,或者一个项目中有多个数据源时,spring容器不知道该注入哪个实现类或者使用哪个数据源,该注解就派上用场。

1)多实现类实现同一接口

 //接口
public interface MemberService {
public Member getMemberById(Long mid);
}
//实现类一
@Service("memberService1")
public class MemberServiceImpl1 implements MemberService{
@Override
public Member getMemberById(Long mid){
//业务代码1
}
}
//实现类二
@Service("memberService2")
public class MemberServiceImpl2 implements MemberService{
@Override
public Member getMemberById(Long mid){
//业务代码2
}
}
//调用类
@Controller("/member")
public class MemberController{
@Autowired
@Qualifier("memberService2") //此处如果不使用该注解则报错,原因就是容器不知道注入哪一个实现类
private MemberService memberService; @PostMapping(value = "/getMember",produces ={MediaType..APPLICATION_JSON_VALUE})
public Response getMember(Long mid){
return new Response().setDate(memberService.getMemberById(mid));
}
}
05-28 16:56