问题
I've got an application context already initialized and I need to load another beans from xml definition into it in addition.
I can do applicationContext.getAutowireCapableBeanFactory() but it is just for autowiring properties of some Object.
I can't find how to do that via XmlBeanDefinitionReader and ContextLoader, because as you can see, only public method is loadContext(String... locations) and it always creates a new context.
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;
}
回答1:
You have to "merge" your two ApplicationContext by setting your created context as child of the parent context and refresh the parent:
GenericApplicationContext context = new GenericApplicationContext();
context.setParent(parentContext);
parentContext.refresh();
回答2:
If I understand that correctly, you want to load beans from xml locations to an already existing application context. You just go like this afaik :
ApplicationContext context;
BeanDefinitionReader beanDefReader = new XmlBeanDefinitionReader(context) ;
beanDefReader.loadBeanDefinitions(locations);
context.refresh();
来源:https://stackoverflow.com/questions/6973783/register-additional-beans-from-xml-definition-into-application-context-that-is-a