2016-04-25 139 views
1

我在我的Spring Java模塊如何在Spring中將兩個ApplicationContext合併到另一箇中?

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
      "SpringBeans.xml"); 

ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml"); 

兩個不同的XML文件兩個上下文。現在,我必須從context獲取HelloBeans.xml的bean以及從helloContext獲取SpringBeans.xml的bean,而無需刷新上下文。

+0

請看看 - http://stackoverflow.com/questions/6973783/register-additional-beans-from -xml-definition-into-application-context-that-is-a – asg

+0

設置父項只允許一種方式訪問​​,不能通過父項訪問子項的bean –

回答

0

您可以創建一個父Spring上下文文件(例如AllBeans.xml)和進口SpringBeans.xmlHelloBeans.xml

<import resource="classpath:SpringBeans.xml" /> 
<import resource="classpath:HelloBeans.xml" /> 

和代碼將成爲:

ClassPathXmlApplicationContext SuperContext = new ClassPathXmlApplicationContext("AllBeans.xml"); 
+0

我只能使用'context'和'helloContext' –

0

嘗試下面的代碼,使用「helloContext 「最後:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); 
ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml"); 

helloContext.setParent(context); 
helloContext.setClassLoader(context.getClassLoader()); 
helloContext.refresh(); 
helloContext.registerShutdownHook(); 
+0

沒有用,已經試過了一切 –

+0

我的測試用例沒問題,請顯示你的代碼或配置。 –

+0

我必須從'helloContext'中從'context'和SpringBeans.xml的bean中獲取HelloBeans.xml的bean而不刷新上下文(兩種方式或換句話說 - 反之亦然) –

1

找不到我一直在尋找,但是這是最好的,我可以這樣做:

PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(
      context.getClassLoader()); 
Resource resource = pathMatchingResourcePatternResolver 
      .getResource("classpath:HelloBeans.xml"); 
AutowireCapableBeanFactory factory = context 
      .getAutowireCapableBeanFactory(); 
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; 
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(
      registry); 
xmlReader.loadBeanDefinitions(resource); 
相關問題