如何在Spring中将两个ApplicationContext合并到另一个中?

问题描述:

我在我的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://*.com/questions/6973783/register-additional-beans-from -xml-definition-into-application-context-that-is-a – asg

+0

设置父项只允许一种方式访问​​,不能通过父项访问子项的bean –

您可以创建一个父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' –

尝试下面的代码,使用“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而不刷新上下文(两种方式或换句话说 - 反之亦然) –

找不到我一直在寻找,但是这是最好的,我可以这样做:

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