How to add bean instance at runtime in spring WebApplicationContext?

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

Leave a Comment