英文:
Spring @Qualifer not working with Bean implementing multiple interface
问题
我有一个实现了两个接口的 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;
}
无论是否使用 Qualifier,我都会得到以下错误:
UnsatisfiedDependencyException: Error creating bean with name a... nosuchbeandefinitionexception
英文:
I have a bean which implements two interfaces. Below is my code-
@Qualifier("A")
interface InterfaceA {
method a()
}
@Qualifier("B")
interface InterfaceB {
method b()
}
public class ClassC implements InterfaceA, InterfaceB {
method a(){}
method b(){}
}
When I inject my bean in some other class, say
public class MyClass {
@Autowired
@Qualifier("A")
private InterfaceA a;
@Autowired
@Qualifier("B")
private InterfaceA b;
}
I get below error whether I use Qualifier or not
UnsatisfiedDependencyException: Error creating bean with name a... nosuchbeandefinitionexception
答案1
得分: 1
通过使用 @Qualifier
注解,我们可以消除哪个 Bean 需要被注入的问题。因此,它与位于类上方的 @Component
注解一起使用,而不是与接口一起使用。
在您的情况下,您只有一个类 ClassC
,它实现了两个接口 InterfaceA
和 InterfaceB
。
因此,为了解决这个问题,您需要将 @Component
添加到 ClassC
:
@Component
public class ClassC implements InterfaceA, InterfaceB {
method a(){}
method b(){}
}
最后,您应该从 MyClass
、InterfaceA
和 InterfaceB
中删除所有的 @Qualifier
注解。
查看这个链接,了解更多关于如何使用 @Qualifier
的信息。
英文:
By using the @Qualifier
annotation, we can eliminate the issue of which bean needs to be injected. So it is used with @Component
annotation above classes, not interfaces.
In your case, you have just one class ClassC
that implements two interfaces InterfaceA
and InterfaceB
.
So to resolve the issue, you need to add @Component
to ClassC
:
@Component
public class ClassC implements InterfaceA, InterfaceB {
method a(){}
method b(){}
}
And finally, you should remove all @Qualifier
annotations, from MyClass
and InterfaceA
and InterfaceB
.
Take look at this to know more about how to use @Qualifier
.
答案2
得分: 0
@Component缺失在您的类C上。同时确保您的组件扫描覆盖了类C所在的包。
英文:
@Component is missing on your class C. Also make sure your component scan covers the package in which class C is present.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论