【问题标题】:How to merge two ApplicationContext into one another in Spring?如何在 Spring 中将两个 ApplicationContext 合并到另一个中?
【发布时间】:2016-04-25 07:56:15
【问题描述】:

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

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

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

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

【问题讨论】:

标签: java xml spring


【解决方案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);

【讨论】:

  • 您找到解决方案了吗?欢迎分享。
【解决方案2】:

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

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

代码会变成:

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

【讨论】:

  • 我只能使用context helloContext
【解决方案3】:

尝试下面的代码,最后使用“helloContext”:

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

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

【讨论】:

  • 我的测试用例没问题,请出示你的代码或配置。
  • 我必须在不刷新上下文的情况下从 context 获取 HelloBeans.xml 的 bean 和从 helloContext 获取 SpringBeans.xml 的 bean。(两种方式或换句话说 - 反之亦然)
猜你喜欢
  • 2022-07-08
  • 1970-01-01
  • 2016-07-26
  • 2011-06-03
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2012-10-17
  • 2016-11-18
相关资源
最近更新 更多