【问题标题】:NoUniqueBeanDefinitionException: ... expected single matching bean but found 2:NoUniqueBeanDefinitionException: ... 预期单个匹配 bean 但找到 2:
【发布时间】:2016-04-12 20:52:11
【问题描述】:

我有这个超类:

@Component
public class DAOBase {
}

另外一个类扩展了 DAOBase

@Component
public class VoceDAO extends DAOBase{       
}

当我这样AutoWired类DAOBase时

@Service
public class TransactionService {
    @Autowired
    private DAOBase dAOBase;
}

我收到此错误:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.jeansedizioni.dao.DAOBase] is defined: expected single matching bean but found 2: DAOBase,voceDAO
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:865)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 37 more

阅读一些帖子我发现了这个解决方案:

@Component("DAOBaseBeanName")
public class DAOBase {
}

我想确定我完全理解解决方案。 对于@Component("DAOBaseBeanName"),我为DAOBase 类指定了特定名称“DAOBaseBeanName”,应用程序可以使用该名称识别DAOBase 类,以免与扩展DAOBase 的其他类混淆。对吗?

谢谢。

【问题讨论】:

  • 恕我直言,您的 DAOBase 应该是 abstract 并且没有 @Component 注释...旁边,您应该在服务中使用具体类型 VoceDao 而不是基类.

标签: java spring-mvc autowired


【解决方案1】:

尝试像这样添加@Qualifier注解:

 @Autowired
 @Qualifier("dAOBase")
 private DAOBase dAOBase;

指定要在类中注入哪个beanDAOBasevoceDAO)。

【讨论】:

    【解决方案2】:

    是的,就像你写的那样。您还可以在使用 Qualifier 注释自动装配 bean 时指定要注入的实现。

    【讨论】:

      【解决方案3】:

      @Resource(name = "{your child class name}") 有效而@Autowired 有时无效的原因是它们的匹配顺序不同

      @Autowire 的匹配序列
      类型、限定符、名称

      @Resource 的匹配序列
      名称、类型、限定符

      更详细的解释可以在这里找到:
      Inject and Resource and Autowired annotations

      在这种情况下,从父类或接口继承的不同子类会混淆@Autowire,因为它们来自同一类型;由于 @Resource 使用 Name 作为第一个匹配优先级,它可以工作。

      【讨论】:

        猜你喜欢
        • 2018-04-22
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        • 2021-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多