我已经初始化了一个应用程序上下文,并且我还需要从 xml 定义加载另一个 bean 到其中。
我可以执行 applicationContext.getAutowireCapableBeanFactory() 但它仅用于某些对象的 Autowiring 属性。
我无法找到如何通过 XmlBeanDefinitionReader 和 ContextLoader 执行此操作,因为如您所见,只有 public 方法是 loadContext(String...locations)
并且它总是创建一个新上下文。
public final ConfigurableApplicationContext loadContext(String... locations) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Loading ApplicationContext for locations [" +
StringUtils.arrayToCommaDelimitedString(locations) + "].");
}
GenericApplicationContext context = new GenericApplicationContext();
prepareContext(context);
customizeBeanFactory(context.getDefaultListableBeanFactory());
createBeanDefinitionReader(context).loadBeanDefinitions(locations);
AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
customizeContext(context);
context.refresh();
context.registerShutdownHook();
return context;
}
最佳答案
您必须通过将创建的上下文设置为父上下文的子上下文并刷新父上下文来“合并”两个 ApplicationContext:
GenericApplicationContext context = new GenericApplicationContext();
context.setParent(parentContext);
parentContext.refresh();
关于java - 将 xml 定义中的附加 bean 注册到已初始化的应用程序上下文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6973783/