How can i remove a singleton spring bean from ApplicationContext?
Removing definition does both : removing definition and destroying (removing all container references on that bean) corresponding Singleton :
((BeanDefinitionRegistry) beanFactory).removeBeanDefinition("myBean");
If you just need to remove the singleton then :
((DefaultListableBeanFactory) beanFactory).destroySingleton("myBean");
The latter way may be especially useful if you just registered singleton but haven't defined any bean definitions, i.e.
((SingletonBeanRegistry) beanFactory).registerSingleton("myBean", myBeanInstance);
You can try removing the bean definition. Get the BeanDefinitionRegistry
and call removeDefinition(..)
It depends on the way you create your application, but for example in web application you can get the definition registry by:
BeanDefinitionRegistry factory =
(BeanDefinitionRegistry) applicationCtx.getAutowireCapableBeanFactory();
(the bean factory implements BeanDefinitionRegistry
).
I don't know if the bean instance will be removed as well. Give it a try.