How can i remove a singleton spring bean from ApplicationContext?

一个人想着一个人 提交于 2019-11-26 18:58:06

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.

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); 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!