全部,
我有一个 applicationContext 并且其中的 bean 在我的应用程序启动时被初始化 - 我将调用这个父上下文。
我有另一个 applicationContext(辅助)——它在运行时部署到我的应用程序中——其中的 beans 是手动读取并加载到我的父上下文中的,我这样做是预先加载所有 beans,然后将它们注册为单例我的父上下文 - 下面显示了一个片段。这按预期工作。
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 作为我的辅助上下文中的属性引用传递) - 但是当我这样做时,我得到一个'No bean named ' 异常(exception)。这是显而易见的,因为次要上下文不知道父上下文。
我已经尝试在辅助上下文中为 bean 设置 lazy-init="true"- 但这没有帮助 - 有人可以建议如何克服这个问题吗?
问候
最佳答案
如果你从子上下文中引用一些父 bean,你只需要说出关于你父 bean 的子上下文:
ConfigurableApplicationContext parentConfContext = (ConfigurableApplicationContext)parentContext;
ApplicationContext fileContext =
new FileSystemXmlApplicationContext(new String[] {"file:" + fileList.get(i).getPath()},
parentConfContext);
关于java - 如何在运行时在不同的上下文中引用 Spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33739584/