将其他bean从xml定义注册到已初始化的应用程序上下文中

lis*_*sak 0 java spring javabeans

我已经初始化了一个应用程序上下文,我还需要从xml定义中加载另一个bean.

我可以执行applicationContext.getAutowireCapableBeanFactory(),但它只适用于某些Object的自动装配属性.

我无法通过XmlBeanDefinitionReader和ContextLoader找到如何做到这一点,因为正如您所看到的,只有公共方法是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;
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*ers 5

您必须通过将创建的上下文设置为父上下文的子项来"合并"您的两个ApplicationContext并刷新父项:

GenericApplicationContext context = new GenericApplicationContext();
context.setParent(parentContext);
parentContext.refresh();
Run Code Online (Sandbox Code Playgroud)