【问题标题】:How to refer a Spring bean at run time in a different context如何在运行时在不同的上下文中引用 Spring bean
【发布时间】:2015-11-16 16:01:38
【问题描述】:

全部,

我有一个 applicationContext 并且其中的 bean 在我的应用程序启动时被初始化 - 我将调用这个父上下文。

我有另一个 applicationContext(辅助) - 这在运行时部署到我的应用程序中 - 其中的 bean 被手动读取并加载到我的父上下文中,我这样做是预先加载所有 bean,然后将它们注册为单例我的父上下文 - sn-p 如下所示。这按预期工作。

ApplicationContext fileContext = new     FileSystemXmlApplicationContext("file:" + fileList.get(i).getPath());
Map<String, List> beansOfType = fileContext.getBeansOfType(List.class, false, false);
String[] beanNames = fileContext.getBeanDefinitionNames();
ConfigurableApplicationContext parentConfContext = (ConfigurableApplicationContext)parentContext;
BeanDefinitionRegistry beanReg = (BeanDefinitionRegistry)parentConfContext.getAutowireCapableBeanFactory();
for (String string : beanNames) {
try {
    beanReg.removeBeanDefinition(string);
} 
catch (NoSuchBeanDefinitionException e) {
// TODO Auto-generated catch block
}
parentConfContext.getBeanFactory().registerSingleton(string,     fileContext.getBean(string));
}

现在我想在我的辅助应用程序上下文中引用我的父上下文中的一个 bean(我将父上下文中的一个 bean 作为我的辅助上下文中的属性引用传递) - 但是当我这样做时,我得到一个“没有命名的 bean ' 例外。这很明显,因为辅助上下文不知道父上下文。

我已尝试在辅助上下文中将 lazy-init="true" 设置为 bean - 但这无济于事 - 有人可以建议如何克服这个问题吗?

问候 D

【问题讨论】:

    标签: java spring spring-integration lazy-initialization


    【解决方案1】:

    如果你从子上下文中引用一些父 bean,你只需要说那个子上下文关于你的父:

    ConfigurableApplicationContext parentConfContext = (ConfigurableApplicationContext)parentContext;
    
    ApplicationContext fileContext = 
        new FileSystemXmlApplicationContext(new String[] {"file:" + fileList.get(i).getPath()}, 
                               parentConfContext);
    

    【讨论】:

      【解决方案2】:

      在 Spring 中,上下文是独立的。如果你想在两个上下文中加载一个 bean,你需要一个通用的配置文件/类。

      例如,您有一个文件/类 A,用于第一个上下文,一个文件/类 B 用于第二个上下文。然后,如果您有一个需要在 A 和 B 上下文中的 bean,您需要具有该 bean 定义的第三个文件/类 C。最后,您需要将文件/类 C 导入 A 和 B。

      https://spring.io/understanding/application-context

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-18
        • 2015-02-06
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 2018-04-03
        相关资源
        最近更新 更多