36

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 ?

jackalope
  • 1,554
  • 3
  • 17
  • 37
  • 1
    This is a highly peculiar thing to do. What are you trying to achieve? if you give us a higher-level description, maybe we can suggest a more conventional alternative. – skaffman Jul 28 '11 at 08:18

2 Answers2

56

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); 
lisak
  • 21,611
  • 40
  • 152
  • 243
31

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140