当前位置: 首页 > 知识库问答 >
问题:

未定义类型的唯一bean:预期为单个匹配bean,但发现2[重复]

秦景福
2023-03-14
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.belk.api.adapter.contract.Adapter] is defined: expected single matching bean but found 2: [endeca, solar]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 64 more
 public interface CommonAdapter {
    List service() ;
}
@Component
public class AdapterFactory {
    @Autowired
    Adapter adapter;
    public Adapter getAdapter(String adapterName){
        return adapter;
    }

}   
    <context:component-scan base-package="com.test.api" />
    <bean
        class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean"
        id="adapterFactory">
        <property name="serviceLocatorInterface" value="com.test.api.adapter.manager.AdapterFactory">
        </property>
    </bean>

现在在我的适配器项目中,我有CommonAdapter.java的实现类一个是EndecaAdapetr.java,另一个是SolarAdapter.java

@Component("endeca")
public class EndecaAdapter implements Adapter {
    List service() {
    // My bussiness logic
    }
}

@Component("solar")
public class SolarAdapter implements Adapter {
    List service() {
    // My bussiness logic
    }
}

现在在我的服务项目中,希望基于输入调用上述两个类的服务方法。

public class ProductSearchServiceImpl {
    @Autowired
    private AdapterFactory adapterFactory;
    public Search searchProducts(){
    Adapter endecaAdapter = this.adapterFactory
                .getAdapter("endeca ");
 }
 }

共有1个答案

司徒胤
2023-03-14

@autowired仅在毫无疑问应该注入哪个容器管理的实例时工作。基本上,这可以通过(至少)3种方式实现:

  1. 只有一个容器管理的bean是autowired field的声明类型;
  2. 有更多容器管理的bean验证上述IS-A条件,但autowired字段也是合格的(在Spring中,通过使用@qualifier注释)
  3. 您不使用@autowired,而是按名称注入beans.

在您的示例中,您有两个bean来验证IS-A条件:

Endeca是-适配器

 类似资料: