How to add bean instance at runtime in spring WebApplicationContext?
Instead of autowiring WebApplicationContext you can do
@Autowired
private GenericWebApplicationContext context;
Then you can do register new bean or remove old one and register new bean
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
registry.removeBeanDefinition("myBean");
context.registerBean("myBean", MyBean.class, () -> new MyBean());
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);
}