我的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注入该类?
答案 0 :(得分:2)
private InterfaceB b
A
必须标有@Autowired
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();
}
}