Register additional beans from xml definition into application context that is already initialized

青春壹個敷衍的年華 提交于 2019-12-25 04:04:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!