如何在spring中注入一个bean,它是使用@component标记声明的类的一部分

时间:2014-05-05 05:57:15

标签: spring

我的spring配置设置为使用自动扫描bean。

<context:annotation-config/>
<context:component-scan base-package="mypackage" />

我有一个用@Component

声明的类
@Component
class A{
   private InterfaceB b;
}

InterfaceB是jar文件的一部分。

InterfaceBImpl implements InterfaceB{ 
// some contract here
}

我从春天收到错误,说它找不到类型为InterfaceB的匹配bean。

如何将该bean注入该类?

3 个答案:

答案 0 :(得分:2)

    {li} private InterfaceB b A必须标有@Autowired
  1. 但这还不够,InterfaceBImpl也必须是 bean :或者@Component,或者<bean> xml config。

答案 1 :(得分:0)

您必须在xml中声明类型为 B 的bean。 Spring会在你用@Autowired注释字段的地方自动拾取它。

以下是一个例子:

@Component
class A {

    @Autowired
    private B myB;

    //other code
}

在你的xml中:

<context:annotation-config/>
<context:component-scan base-package="mypackage" />

<bean id="myB" class="mypackage.InterfaceBImpl" />

Spring会看到 A 依赖于 B ,在上下文中查看并看到它有 B 的实现,这是< strong> InterfaceBImpl 并将其注入 A

答案 2 :(得分:0)

如果您可以控制InterfaceBImpl的来源,请添加@Component注释以使Spring创建一个bean可用于自动连接。

如果InterfaceBImpl无法更改,您可以1)扩展它并注释扩展名;或者2)您可以创建创建bean的配置:

1)

@Component
class MyInterfaceBImpl extends InterfaceBImpl {
}

2)

@Configuration
class MyAdditinalBeans {
  @Bean
  public InterfaceB interfaceB() {
    return new InterfaceBImpl();
  }
}