Java 如何在春季将两个ApplicationContext合并为另一个?

Java 如何在春季将两个ApplicationContext合并为另一个?,java,xml,spring,Java,Xml,Spring,我的SpringJava模块中有两个上下文 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "SpringBeans.xml"); 及 使用两个不同的xml文件。现在,我必须从context获取HelloBeans.xml的bean,从helloContext获取SpringBeans.xml的bean,而无需刷新上下文。您可以创建一个父spring上下文文件(例如

我的SpringJava模块中有两个上下文

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


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

您可以创建一个父spring上下文文件(例如
AllBeans.xml
)并导入
SpringBeans.xml
HelloBeans.xml

<import resource="classpath:SpringBeans.xml" />
<import resource="classpath:HelloBeans.xml" />
尝试以下代码,最后使用“helloContext”:


找不到我要找的东西,但这是我能做的最好的:

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

我必须使用
context
helloContext
only请看一看-设置父项将只允许单向访问,您不能通过父项访问子项的bean在我的测试用例中没有问题,请显示您的代码或配置。我必须从
context
获取HelloBeans.xml的bean,并从
helloContext
获取SpringBeans.xml的bean,而无需刷新上下文。(两种方法都可以,或者换句话说,反之亦然)您找到解决方案了吗?请分享。
ClassPathXmlApplicationContext SuperContext = new ClassPathXmlApplicationContext("AllBeans.xml");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");
ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml");

helloContext.setParent(context);
helloContext.setClassLoader(context.getClassLoader());
helloContext.refresh();
helloContext.registerShutdownHook();
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);