How to add a bean instance at runtime in spring WebApplicationContext?

So the name is pretty simple. I have a handler class DynamicBeanHandlerthat implements the interface BeanDefinitionRegistryPostProcessorprovided by spring. In this class, I add some SCOPE_SINGLETONbeans that have the bean class set as MyDynamicBeanfollows:

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 MutablePropertyValues.

Later I SpringUtil.getBean(dynamicBeanId)extracted the required instance MyDynamicBeanwhere the SpringUtilclass implements ApplicationContextAware. It all works great. The problem occurs when I want to delete one of these instances and later add a new instance where I do not have a registry instance. Can someone help me find a way to do this?

Below is the code for the 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);
    }
}
+4
1

BeanDefinitionRegistry ( API) beans.

, SpringUtil , bean, removeBeanDefinition(), bean, 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);
}
+7

Source: https://habr.com/ru/post/1673328/


All Articles