SpringFramework:预期单个匹配的bean,但找到了2 [英] SpringFramework: expected single matching bean but found 2

查看:195
本文介绍了SpringFramework:预期单个匹配的bean,但找到了2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个项目,该项目使用SpringFramework从MongoDB中读取数据,其结构如下所示:存储库服务:

I'm building a project read data from MongoDB using SpringFramework, with structure for Repository and Service as below:

Repository:
    + Interfaces: 
        - I <T extends Object>
        - I1 extends I<M1>
        - I2 extends I<M2>
    + Implements: 
        - RI Abstract RI<T extends Object>
        - RI1 extends RI<M1> implements I1
        - RI2 extends RI<M2> implements I2

Service:
    + Interfaces: 
        - SI <T extends Object>
        - SI1 extends SI<M1>
        - SI2 extends SI<M1>
    + Implements:
        - Abstract SIIMPL : @Autowired I<?>
        - SI1IMPL : extends SIIMPL<M1> implements SI1
        - SI2IMPL : extends SIIMPL<M2> implements SI2

我跑步时会抛出异常:

没有可用的'I'类型的合格Bean:预期的单个匹配 豆,但发现2:I1,I2

No qualifying bean of type 'I' available: expected single matching bean but found 2: I1,I2

当我删除RI2时,它可以正常工作.我认为,根本原因是@Autowired从Abstract(SIIMPL)到另一个具有 RI1和RI2是2种执行器,因此spring不知道该选择哪个bean.

When I delete RI2, it work properly. In my opinion, I think the root cause is the @Autowired from Abstract(SIIMPL) to another abstract(I) that have 2 implements are RI1 and RI2 so spring does not know what bean to pick.

如果有人有任何想法,请给我评论.谢谢!

If someone have any idea, please leave me a comment. Thank you!

推荐答案

首先,您应该在Abstract SIIMPL类中使用非通配符的泛型.看起来像这样:

Firstly you should use a generics not wildcarding in the Abstract SIIMPL class. So that it looks like:

public abstract class SIIMPL<T> {

   protected I<T> foo; // Don't autowire here

}

然后如上所述,不要将泛型I对象自动连接到抽象类中,只需在那里定义它,然后通过构造函数注入将其自动连接到您的具体类中即可:

Then as above don't autowire the generic I object into the abstract class just define it there and then autowire it into your concrete classes via constuctor injection:

public class SI1IMPL extends SIIMPL<M1> implements ST1 {

  public ST1IMPL(@Autowired I<M1> foo) {
      this.foo = foo;
  }

}

这篇关于SpringFramework:预期单个匹配的bean,但找到了2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆