解决同一接口有多个实现类的注入问题

4 篇文章 1 订阅

一、前言

解决报错问题

  • 错误信息
  • Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

二、问题原因——多个类实现同一接口

  • 先看代码
    在这里插入图片描述
    在这里插入图片描述
  • 根据上面错误信息再结合代码,可以看出问题就是:
    同一个接口 PetInterface 有两个实现类(DogPlays 和 CatPlays),而我们的Spring并不知道应当引用哪个实现类

三、解决问题

  • 那么上述问题怎么解决呢?
    当然简单粗暴的方法不是不可以——直接删除一个实现类,删除之后,Spring会自动去对应包下寻找 PetInterface 接口的实现类,发现 PetInterface 接口只有一个实现类,便会直接引用这个实现类。删除的前提是你没有别的需求(即:你不需要或者你写多了)。
    当然,如果非留不可,也不是不能解决,请往下继续……

1.方案1:用注解 @Qualifier

(1)代码实现

  • 注意是 @Autowired 与 @Qualifier 二者结合使用,不要漏掉其中一个
	@Qualifier("dogPlays" )
    @Autowired
    private PetInterface petInterface;

    @Qualifier("catPlays" )
    @Autowired
    private PetInterface petInterface2;
  • 看我们的idea智能的过分,哈哈挺好
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

(2)需要注意点 @Service

  • 需要注意的是:
    (1)如果实现类里,注解 @Service 没有指定实现类的 bean 名称,则注入的时候默认用该实现类首字母小写的bean的名字
    (2)如果用注解 @Service(“dog”) 指定了实现类的 bean 名称,则用注解 @Qualifier(“dog”) 注入的时候,注意名称保持一致
  • 具体如下:
    在这里插入图片描述
    在这里插入图片描述
	@Autowired
    @Qualifier("dog")
    private PetInterface petInterface;

    @Autowired
    @Qualifier("catPlays")
    private PetInterface petInterface2;

(3)@Autowired 简单理解

  • @Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired
  • @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作。
  • @Autowired 默认是按照类型去匹配注入,配合 @Qualifier 按照指定的 name 名称去装配 bean。

2.方案2——用注解@Resource

(1)代码实现

  • 用注解 @Resource(name = " ") 或 @Resource(type = ) 替换 @Autowired 、 @Qualifier 这两个组合注解
 	@Resource(name = "dogPlays")
    private PetInterface petInterface;

    @Resource(name = "catPlays")
    private PetInterface petInterface2;

或者:

    @Resource(name = "dogPlays")
    private PetInterface petInterface;

    @Resource(type = CatPlays.class)
    private PetInterface petInterface2;

在这里插入图片描述
在这里插入图片描述

(2)需要注意点 @Service

  • 参考方案1中的需要注意点

(3)@Resource 简单理解

  • @Resource注解由J2EE提供,需要导入包javax.annotation.Resource

  • @Resource 与 @Autowired 差不多,但是@Resource默认按照ByName自动注入

  • 理解 @Resource 自动装配顺序:
    (1)@Resource后面没有任何内容(既没有指定name,又没有指定type),默认通过 name 属性去匹配 bean 进行装配,如果找不到再按 type 去匹配
    (2)如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
    (3)如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。
    (4)如果只指定@Resource注解的type属性,则从上下文中找到类似匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。

  • 参考:
    @Resource注解.

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@素素~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值