【发布时间】: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