我的spring java模块中有两个上下文
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");
和
ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml");
有两个不同的xml文件。现在我必须从context
获取HelloBeans.xml的bean,并从helloContext
获取SpringBeans.xml的bean,而不刷新上下文。
答案 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.xml
和HelloBeans.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();