How to add bean instance at runtime in spring WebA

2020-02-05 03:37发布

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);

The method getMutableProperties() returns an object of MutablePropertyValues.

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?

Following is the code for class 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);
    }
}

1条回答
beautiful°
2楼-- · 2020-02-05 03:56

You can make use of BeanDefinitionRegistry (look here for API) to remove or register the beans dynamically.

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);
}
查看更多
登录 后发表回答