【问题标题】:Spring FactoryBean and autowiring not working : expected single matching bean but found 2Spring FactoryBean 和自动装配不起作用:预期单个匹配 bean 但找到 2
【发布时间】:2014-08-18 18:10:54
【问题描述】:

我有两个类,每个类都通过工厂自动装配同一个类:

@Service
public class AnalyseDispensationNominativeMetierService implements IAnalyseDispensationNominativeMetierService {

  @Autowired
  @Qualifier("interfaceAutomateServiceFactory")
  private IInterfaceAutomateMetierService interfaceAutomateMetierService;
  [...]


@Service
public class AnalysePreparationGlobaleMetierService implements IAnalysePreparationGlobaleMetierService {

  @Autowired
  @Qualifier("interfaceAutomateServiceFactory")
  private IInterfaceAutomateMetierService interfaceAutomateMetierService;
  [...]

我想通过工厂创建的对象:

@Service
public class InterfaceAutomate implements IInterfaceAutomateMetierService {
[...]

工厂:

@Service("interfaceAutomateServiceFactory")
public class InterfaceAutomateServiceFactory implements FactoryBean<IInterfaceAutomateMetierService> {

  @Autowired(required = true)
  private InterfaceAutomate ijinInterfaceAutomate;

  @Override
  public IInterfaceAutomateMetierService getObject() {
    return ijinInterfaceAutomate;
  }

  @Override
  public Class<?> getObjectType() {
    return IInterfaceAutomateMetierService.class;
  }

  @Override
  public boolean isSingleton() {
    return false;
  }

我不断收到以下错误,即使我正在使用限定符注释...知道我做错了什么吗? :

No unique bean of type [IInterfaceAutomateMetierService] is defined: expected single matching bean but found 2: [interfaceAutomate, interfaceAutomateServiceFactory]

完整的堆栈跟踪

GRAVE: Exception lors de l'envoi de l'évènement contexte initialisé (context initialized) à l'instance de classe d'écoute (listener) org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'analysePreparationGlobaleMetierService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dispensation.commun.service.metier.IInterfaceAutomateMetierService dispensation.analysePreparationGlobale.service.metier.impl.AnalysePreparationGlobaleMetierService.interfaceAutomateMetierService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [dispensation.commun.service.metier.IInterfaceAutomateMetierService] is defined: expected single matching bean but found 2: [interfaceAutomate, interfaceAutomateServiceFactory]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dispensation.commun.service.metier.IInterfaceAutomateMetierService dispensation.analysePreparationGlobale.service.metier.impl.AnalysePreparationGlobaleMetierService.interfaceAutomateMetierService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [dispensation.commun.service.metier.IInterfaceAutomateMetierService] is defined: expected single matching bean but found 2: [interfaceAutomate, interfaceAutomateServiceFactory]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 20 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [dispensation.commun.service.metier.IInterfaceAutomateMetierService] is defined: expected single matching bean but found 2: [interfaceAutomate, interfaceAutomateServiceFactory]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:823)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
    ... 22 more

【问题讨论】:

  • 你为什么要这样做:@Autowired(required = true) private InterfaceAutomate ijinInterfaceAutomate;?在InterfaceAutomate 上使用FactoryBean 和@Service 注释有点多余。
  • @user3145373ツ 通过注解完成配置
    你为什么需要InterfaceAutomateServiceFactory类?
  • @AndreiStefan :我没有写代码,我只是想让它工作......
  • (但我认为在某些时候工厂将用于在两种不同的实现之间切换)

标签: java spring annotations factory autowired


【解决方案1】:

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

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

@资源的匹配顺序:
名称、类型、限定符

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

在这种情况下,从父类或接口继承的不同子类会混淆@Autowire,因为它们来自同一类型;

另一方面,@Resource 使用 Name 作为第一个匹配优先级,它可以工作。

【讨论】:

    【解决方案2】:

    在你的 bean 中使用 @Primary 注释(两者中的一个)可以解决这个问题。但是问题仍然存在,为什么 Spring 的 @Resource 注释无法基于自动装配进行区分。

    参考“Autowiring two beans implementing same interface - how to set default bean to autowire?

    【讨论】:

      【解决方案3】:

      最后,我通过更改 factoryBean 的名称以匹配注入字段的名称,并在项目的扫描中删除一个条目来解决我的问题。 (会不会是“双重扫描”惹的祸?)

      <context:component-scan base-package="dispensation.**.factory.**,dispensation.**.metier.factory.**
      

      =>

      <context:component-scan base-package="dispensation.**.factory.**
      

      @Service("interfaceAutomateMetierService")
      public class InterfaceAutomateServiceFactory implements FactoryBean<IInterfaceAutomateMetierService> {
      

      @Service
      public class AnalysePreparationGlobaleMetierService implements IAnalysePreparationGlobaleMetierService {
      
        @Autowired
        private IInterfaceAutomateMetierService interfaceAutomateMetierService;
      

      【讨论】:

      • 由于双重扫描,我也遇到了同样的异常。
      • 我有同样的异常,只是通过更改 factoryBean 的名称来解决它。我怀疑它与组件构造函数的默认实现(空构造函数)冲突。
      【解决方案4】:

      如果您不能或不想修改源代码,请通过在 中添加 来排除明显多余的工厂 bean。 默认通过 隐含。

      【讨论】:

        【解决方案5】:

        代替

        @Autowired
        @Qualifier("interfaceAutomateServiceFactory")
        private IInterfaceAutomateMetierService interfaceAutomateMetierService;
        

        试试这个

        @Resource(name="interfaceAutomateServiceFactory")
        private IInterfaceAutomateMetierService interfaceAutomateMetierService;
        

        【讨论】:

          猜你喜欢
          相关资源
          最近更新 更多
          热门标签