2011-08-11 43 views
4

我有2个组件ABA取决于B。我写的是这样的:Spring中的自动装配和注释配置

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); 

配置

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

<bean class="com.A" autowire="byType" /> 

它工作得很好。现在我想通过注释来配置A。所以我@Component注释添加到A

@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> 

但是B不再注入。可能我应该指定自动装配类型或smt那样。那我该如何解决它?

+0

你会得到一个异常,或者'B'就是'null'吗?两个班都坐在同一个包里吗? –

+0

@Benjamin Muschko Just'null'。在同一个包中。我把所有的课程都放在'com'包中 –

回答

5

你必须使用ApplicationContext而不是纯BeanFactory。似乎BeanFactory不运行后处理器,包括寻找@Autowired注释的那个。我会尽量找一块该文件,在此期间尝试:

new ClassPathXmlApplicationContext("/spring.xml").getBean(B.class); 

BTW @Autowired是制定者,建设者,字段等完全有效的(source):

痕构造函数,字段,setter方法或配置方法由Spring的依赖注入工具自动装配。

+0

非常感谢。它正如我所愿。 –

+1

这是您在http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#context-introduction-ctx-vs-beanfactory之后的文档 –