2011-05-18 122 views
10

我正在處理使用DispatcherServlet引導的Spring MVC Web應用程序。它創建了一個XmlWebApplicationContext負責管理整個應用程序:具有Web應用程序上下文的Spring上下文層次結構

<servlet> 
    <servlet-name>springmvc</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet 
    </servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>classpath:springmvc-servlet.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

現在也有一些模塊,應該在運行時使用ContextSingletonBeanFactoryLocator加載。因此每個模塊都有自己的ClasspathXmlApplicationContext。因此,一個模塊可以引用XmlWebApplicationContext中的bean,它應該附加到XmlWebApplicationContext以形成一個上下文層次結構,其中XmlWebApplicationContext應該扮演父級的角色,而模塊的角色是子級上下文的ClasspathXmlApplicationContext。不幸的是,我無法使用

<beans> 
    <bean id="moduleContext" 
     class="org.springframework.context.support.ClassPathXmlApplicationContext"> 
     <constructor-arg> 
      ... 
     </constructor-arg> 
     <constructor-arg ref="parentContext" /> 
    </bean> 
</beans> 

將它們連接起來,因爲我發現沒有辦法迄今給予WebApplicationContext名稱parentContext。我忽視了一些事情嗎?還是有更好/更簡單的方法來以不同的方式實現相同的目標?

回答

2

如果使用註解,你可以這樣做:

@Inject 
private XmlWebApplicationContext context; 

@Inject 
private List<ClassPathXmlApplicationContext> childs; 

@PostConstruct 
public void refreshContext() { 
    for(ClassPathXmlApplicationContext appContext : childs) { 
     appContext.setParent(context); 
    } 
    context.refresh(); 
} 

你可以不用註釋太多,使用接口的InitializingBean和了ApplicationContextAware。

被修改:childs是按類型自動裝配的,所以Spring將注入所有作爲ClassPathXmlApplicationContext實例的bean。

+0

如果我事先不知道他們,我從哪裏得到'孩子'? – aha 2011-05-18 13:29:14

+0

我試過你建議的代碼。它可以工作,但不會傳播到'ContextSingletonBeanFactoryLocator'。但它的方向是正確的:要走的路不是使用'ContextSingletonBeanFactoryLocator',而是手動加載子上下文(使用'GenericApplicationContext')並將它們附加到'InitializingBean'中的父上下文。 – aha 2011-05-26 10:11:32

相關問題