以编程方式将Bean添加到Spring Web App上下文 [英] Add Bean Programmatically to Spring Web App Context
问题描述
由于插件架构,我正在尝试以编程方式将bean添加到我的webapp中。我有一个通过 @Component
注释创建的Spring bean,我正在实现 ApplicationContextAware
接口。
Because of a plug-in architecture, I'm trying to add a bean programmatically to my webapp. I have a Spring bean created through the @Component
annotation, and i am implementing the ApplicationContextAware
interface.
我的覆盖函数如下所示:
My override function looks like this:
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
// this fails
this.applicationContext = (GenericWebApplicationContext) applicationContext;
}
基本上,我无法弄清楚如何将bean添加到applicationContext给setApplicationContext的对象。任何人都可以告诉我这是怎么回事吗?
Basically, I can't figure out how to add a bean to the applicationContext object given to setApplicationContext. Can anyone tell me how I am going about this the wrong way?
好的,这就是我最终得到的解决方案:
Ok, this is what i ended up with as the solution:
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry bdr)
throws BeansException {
BeanDefinition definition = new RootBeanDefinition(
<My Class>.class);
bdr.registerBeanDefinition("<my id>", definition);
}
推荐答案
在Spring 3.0中你可以制作你的bean工具 BeanDefinitionRegistryPostProcessor
并通过 BeanDefinitionRegistry
添加新bean。
In Spring 3.0 you can make your bean implement BeanDefinitionRegistryPostProcessor
and add new beans via BeanDefinitionRegistry
.
在以前的Spring版本中,你可以在 BeanFactoryPostProcessor
中做同样的事情(虽然你需要强制转换 BeanFactory
到 BeanDefinitionRegistry
,可能会失败)。
In previous versions of Spring you can do the same thing in BeanFactoryPostProcessor
(though you need to cast BeanFactory
to BeanDefinitionRegistry
, which may fail).
这篇关于以编程方式将Bean添加到Spring Web App上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!