【问题标题】:Spring @Qualifer not working with Bean implementing multiple interfaceSpring @Qualifer 不与实现多个接口的 Bean 一起使用
【发布时间】:2020-10-23 09:52:13
【问题描述】:

我有一个实现两个接口的 bean。以下是我的代码-

@Qualifier("A")
interface InterfaceA {
    method a()
}

@Qualifier("B")
interface InterfaceB {
   method b()
}

public class ClassC implements InterfaceA, InterfaceB {
   method a(){}
   method b(){}
}

当我在其他类中注入我的 bean 时,说

public class MyClass {

    @Autowired
    @Qualifier("A")
    private InterfaceA a;

    @Autowired
    @Qualifier("B")
    private InterfaceA b;
  
}

无论我是否使用限定符,都会出现以下错误

UnsatisfiedDependencyException:创建名称为 a 的 bean 时出错... nosuchbeandefinitionexception

【问题讨论】:

  • 你在这里的目标是什么?你为什么要注入接口?您期望的行为到底是什么?
  • 我想通过注入接口 A 或 B 来调用接口 A 或 B 的相应方法,无论是否使用 @Qualifier。但是当我尝试使用或不使用限定符进行注入时,它会引发上述异常
  • 你不能调用接口的方法,除非你提供一个实现,因此在Spring容器中创建的bean应该是接口的实现而不是接口本身。请参阅下面@Ismail 的答案。

标签: java spring spring-boot dependency-injection autowired


【解决方案1】:

通过使用@Qualifier注解,我们可以消除需要注入哪个bean的问题。所以它与类上面的@Component注解一起使用,而不是接口。

在您的情况下,您只有一个类 ClassC 实现了两个接口 InterfaceAInterfaceB

所以要解决这个问题,你需要将@Component添加到ClassC

@Component
public class ClassC implements InterfaceA, InterfaceB {
   method a(){}
   method b(){}
}

最后,您应该从MyClassInterfaceAInterfaceB 中删除所有@Qualifier 注释。

查看this,了解更多有关如何使用@Qualifier的信息。

【讨论】:

    【解决方案2】:

    您的 C 类缺少@Component。还要确保您的组件扫描涵盖了 C 类所在的包。

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多