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

时间:2016-04-25 07:56:16

标签: java xml spring

我的spring java模块中有两个上下文

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

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

有两个不同的xml文件。现在我必须从context获取HelloBeans.xml的bean,并从helloContext获取SpringBeans.xml的bean,而不刷新上下文。

3 个答案:

答案 0 :(得分:2)

无法找到我要找的东西,但这是我能做的最好的事情:

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

答案 1 :(得分:1)

您可以创建父春季上下文文件(例如AllBeans.xml)并导入SpringBeans.xmlHelloBeans.xml

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

代码将成为:

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

答案 2 :(得分:1)

尝试下面的代码,使用&#34; helloContext&#34;最后:

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

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