Spring的@Qualifier与实现多个接口的Bean无法正常工作。

huangapple go评论75阅读模式
英文:

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,它实现了两个接口 InterfaceAInterfaceB

因此,为了解决这个问题,您需要将 @Component 添加到 ClassC

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

最后,您应该从 MyClassInterfaceAInterfaceB 中删除所有的 @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.

huangapple
  • 本文由 发表于 2020年10月23日 17:52:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定