2011-08-11 41 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之後的文檔 –