title: How to add bean instance at runtime in spring WebApplicationContext?
body: <p>So, the title is pretty straightforward. I have a handler class <code>DynamicBeanHandler</code> which implements <code>BeanDefinitionRegistryPostProcessor</code> interface provided by spring. In this class I'm adding multiple <code>SCOPE_SINGLETON</code> beans which have bean class set as <code>MyDynamicBean</code> as follows-</p>
  
  <pre><code>GenericBeanDefinition myBeanDefinition = new GenericBeanDefinition();
  myBeanDefinition.setBeanClass(MyDynamicBean.class);
  myBeanDefinition.setScope(SCOPE_SINGLETON);
  myBeanDefinition.setPropertyValues(getMutableProperties(dynamicPropertyPrefix));
  registry.registerBeanDefinition(dynamicBeanId, myBeanDefinition);
  </code></pre>
  
  <p>The method <code>getMutableProperties()</code> returns an object of <code>MutablePropertyValues</code>.</p>
  
  <p>Later on, I do <code>SpringUtil.getBean(dynamicBeanId)</code> to fetch the required <code>MyDynamicBean</code> instance where <code>SpringUtil</code> class implements <code>ApplicationContextAware</code>. 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?</p>
  
  <p>Following is the code for class <code>SpringUtil</code>-</p>
  
  <pre><code>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 &lt;T&gt; T getBean(String beanId, Class&lt;T&gt; beanClass) {
          return applicationContext.getBean(beanId, beanClass);
      }
  }
  </code></pre>