如何在Spring WebApplicationContext中的运行时添加bean实例? [英] How to add bean instance at runtime in spring WebApplicationContext?
问题描述
因此,标题非常简单.我有一个处理程序类DynamicBeanHandler
,它实现了spring提供的BeanDefinitionRegistryPostProcessor
接口.在此类中,我添加了多个SCOPE_SINGLETON
bean,它们的bean类设置为MyDynamicBean
,如下所示-
So, the title is pretty straightforward. I have a handler class DynamicBeanHandler
which implements BeanDefinitionRegistryPostProcessor
interface provided by spring. In this class I'm adding multiple SCOPE_SINGLETON
beans which have bean class set as MyDynamicBean
as follows-
GenericBeanDefinition myBeanDefinition = new GenericBeanDefinition();
myBeanDefinition.setBeanClass(MyDynamicBean.class);
myBeanDefinition.setScope(SCOPE_SINGLETON);
myBeanDefinition.setPropertyValues(getMutableProperties(dynamicPropertyPrefix));
registry.registerBeanDefinition(dynamicBeanId, myBeanDefinition);
方法getMutableProperties()
返回对象MutablePropertyValues
.
稍后,我执行SpringUtil.getBean(dynamicBeanId)
来获取所需的MyDynamicBean
实例,其中SpringUtil
类实现了ApplicationContextAware
.所有这些都很好.当我要删除其中一个实例并在以后没有注册表实例的位置添加新实例时,就会出现问题.有人可以帮我找到一种方法吗?
Later on, I do SpringUtil.getBean(dynamicBeanId)
to fetch the required MyDynamicBean
instance where SpringUtil
class implements ApplicationContextAware
. All this works great. The problem comes when I want to remove one of these instances and add a new instance later on where I don't have the registry instance. Can anyone please help me find a way to do this?
以下是SpringUtil
-
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) {
return applicationContext.getBean(beanId);
}
public static <T> T getBean(String beanId, Class<T> beanClass) {
return applicationContext.getBean(beanId, beanClass);
}
}
推荐答案
您可以使用BeanDefinitionRegistry
(请参阅
You can make use of BeanDefinitionRegistry
(look here for API) to remove or register the beans dynamically.
因此,在您的SpringUtil
类中,您可以添加以下方法以使用removeBeanDefinition()
删除现有的bean定义,然后通过使用registerBeanDefinition()
添加新的bean定义.
So, in your SpringUtil
class, you can add the below method to remove the existing bean definition using removeBeanDefinition()
and then add a new bean definition by using registerBeanDefinition()
.
public void removeExistingAndAddNewBean(String beanId) {
AutowireCapableBeanFactory factory =
applicationContext.getAutowireCapableBeanFactory();
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
registry.removeBeanDefinition(beanId);
//create newBeanObj through GenericBeanDefinition
registry.registerBeanDefinition(beanId, newBeanObj);
}
这篇关于如何在Spring WebApplicationContext中的运行时添加bean实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!