Spring 中的自动装配和注释配置
我有 2 个组件 A
和 B
。 A
取决于 B
。我写了类似的东西:
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
@Component
public class B {}
new XmlBeanFactory(new FileSystemResource("./spring.xml")).getBean(A.class);
config
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
<bean class="com.A" autowire="byType" />
它工作得很好。现在我也想通过注释配置 A
。因此,我向 A
添加了 @Component 注释
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
,并从配置中删除了 A
描述。所以只是
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
But B不再注射了。也许我应该指定自动装配类型或 smt 之类的。那么我该如何修复它呢?
I have 2 components A
and B
. A
depends on B
. I wrote something like:
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
@Component
public class B {}
new XmlBeanFactory(new FileSystemResource("./spring.xml")).getBean(A.class);
config
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
<bean class="com.A" autowire="byType" />
It worked perfectly well. Now I want configure A
by annotations too. So I add @Component annotation to A
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
And removed A
description from configuration. So it just
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
But B doesn't injected anymore. Probably I should specify autowiring type or smt like that. So how I can fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
ApplicationContext
而不是普通的BeanFactory
。似乎 BeanFactory 不运行后处理器,包括寻找 @Autowired 注释的后处理器。我将尝试为此找到一份文档,同时尝试:BTW
@Autowired
在设置器、构造函数、字段等上完全有效。(来源):You have to use
ApplicationContext
instead of plainBeanFactory
. Seems likeBeanFactory
does not run post processors, including the one looking for@Autowired
annotation. I will try to find a piece of documentation for that, in the meantime try:BTW
@Autowired
is completely valid on setters, constructors, fields, etc. (source):我认为你应该尝试
你可以参考下面链接的示例:
http://www.roseindia.net/tutorial/spring/spring3/ioc /autoscanig.html
I think you should try
You can refer to example on below link:
http://www.roseindia.net/tutorial/spring/spring3/ioc/autoscanig.html