I want to develop a module control system so that every spring bean can be managed by my own LifeCycle Controller.
But I can not figure out how can I remove a singleton spring bean out of ApplicationContext.
That may be an interesting problem , can you help me to resolve ?
Remove bean using Spring BeanDefinitionRegistry To register a new bean definition, use registerBeanDefinition . registry. registerBeanDefinition(beanId, newBeanObj); To remove an existing bean definition, use removeBeanDefinition .
The Java heap, as we know, is a globally shared memory accessible to all the running threads within an application. When the Spring container creates a bean with the singleton scope, the bean is stored in the heap. This way, all the concurrent threads are able to point to the same bean instance.
Singleton beans does not provide thread safety and now you know that instance variables usage may lead to unexpected result, you have 2 options to solve the same : Don't use instance variables in multithreaded environment.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With