如何从 ApplicationContext 中删除单例 spring bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6855811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:36:07  来源:igfitidea点击:

How can i remove a singleton spring bean from ApplicationContext?

springlifecycle

提问by Hymanalope

I want to develop a module control systemso that every spring bean can be managed by my own LifeCycle Controller.

我想开发一个模块控制系统,让每个 spring bean 都可以由我自己的 LifeCycle Controller 管理。

But I can not figure out how can I remove a singleton spring bean out of ApplicationContext.

但我不知道如何从 ApplicationContext 中删除一个单例 spring bean。

That may be an interesting problem , can you help me to resolve ?

这可能是一个有趣的问题,你能帮我解决吗?

采纳答案by Bozho

You can try removing the bean definition. Get the BeanDefinitionRegistryand call removeDefinition(..)

您可以尝试删除 bean 定义。获取BeanDefinitionRegistry并调用removeDefinition(..)

It depends on the way you create your application, but for example in web application you can get the definition registry by:

这取决于您创建应用程序的方式,但例如在 Web 应用程序中,您可以通过以下方式获取定义注册表:

BeanDefinitionRegistry factory = 
   (BeanDefinitionRegistry) applicationCtx.getAutowireCapableBeanFactory();

(the bean factory implements BeanDefinitionRegistry).

(bean 工厂实现BeanDefinitionRegistry)。

I don't know if the bean instance will be removed as well. Give it a try.

我不知道 bean 实例是否也会被删除。试一试。

回答by lisak

Removing definition does both : removing definition and destroying (removing all container references on that bean) corresponding Singleton :

删除定义同时执行:删除定义和销毁(删除该 bean 上的所有容器引用)对应的 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.

如果您刚刚注册了单例但尚未定义任何 bean 定义,则后一种方式可能特别有用,即

((SingletonBeanRegistry) beanFactory).registerSingleton("myBean", myBeanInstance);