2011-03-21 48 views
7

我們使用@Configuration類來執行基於Java的Spring配置。我正在嘗試設置AnnotationConfigApplicationContext(s)的層次結構。基於註解的配置層次結構

它似乎工作。正如我可以從父上下文自動裝入Bean作爲從其中一個子上下文創建的bean的成員。

但是我沒有管理從父上下文自動連接Bean到@Configuration類文件,這非常方便。他們都是空的。

// parent context config 
@Configuration 
public class ParentContextConfig{ 
    @Bean parentBeanOne... 
    @Bean parentBeanTwo... 
} 

// child context config 
@Configuration 
public class ChildContextConfig{ 
    @Autowired parentBeanOne 

    @Bean childBeanOne... 
} 

// a sample bean 
@Component 
public class ChildBeanOne{ 
    @Autowired parentBeanTwo 
} 

在此示例中,我所得到的是parentBeanTwoparentBeanOne沒有自動裝配(null)到配置文件正確創建。

我錯過了什麼?

+0

您是如何設置父母/子女關係的? – skaffman 2011-03-21 10:26:24

+0

我發現如果在父上下文中將這些AnnotationConfigApplicationContext聲明爲bean,則自動裝配到ChildContexts的作品將發揮作用。不過,我開始獲得「循環參考?」相關的例外...我無法識別任何循環引用。 – Rafael 2011-03-21 11:42:19

+0

我在註冊@configurable配置類之前通過執行setParent(ctx)來設置關係。 – Rafael 2011-03-21 11:43:26

回答

0

我認爲Spring希望您使用標準的Java層次結構規則來建立配置對象的父子關係。也就是說,讓子配置類擴展父配置類。

+0

Yeahh,但那不完全是一回事。因爲整個類層次結構將在同一個Spring上下文中。在某些情況下,您希望子上下文訪問父上下文,而不是其他方式,例如使用servlet容器等。 – Rafael 2011-03-30 12:01:15

+1

是否有任何新的開發?這似乎是一個基本的配置要求。 – Eugen 2011-11-15 15:40:46

0

對於這個工作,你的孩子應該情境導入父上下文,例如:

@Configuration 
@Import(ParentContextConfig.class) 
public class ChildContextConfig{ 
    @Autowired parentBeanOne 
    ... 
    } 

參考Spring實況更多的相關信息約@Configuration