Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove a singleton spring bean from ApplicationContext?

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 ?

like image 575
jackalope Avatar asked Jul 28 '11 08:07

jackalope


People also ask

How do I remove a bean from context?

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 .

How singleton beans work in multi threading applications?

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.

Does singleton from Spring container is thread safe?

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.


1 Answers

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);  
like image 71
lisak Avatar answered Oct 21 '22 10:10

lisak