Java 如何重新初始化 Spring Bean?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51218086/
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-08-11 00:00:42  来源:igfitidea点击:

How to reinitialize a Spring Bean?

javaspringspring-bootspring-bean

提问by Fip

Is it possible to reinitialize a Spring Bean on runtime?

是否可以在运行时重新初始化 Spring Bean?

My Bean uses static settings which in some cases changes and then i have to reinitialize the bean.

我的 Bean 使用静态设置,在某些情况下会发生变化,然后我必须重新初始化 bean。

采纳答案by Amith Kumar

You have three options to update singleton bean in spring context, you can chose one suitable for your use case:

您有三个选项可以在 spring 上下文中更新单例 bean,您可以选择一个适合您的用例:

Reload method In the Bean
Create a method in your bean which will update/reload its properties. Based on your trigger, access the bean from spring context, and then call the reload method to update bean properties (since singleton) it will also be updated in spring context & everywhere it is autowired/injected.

在 Bean 中重新加载方法 在您的 Bean 中
创建一个方法,该方法将更新/重新加载其属性。根据您的触发器,从 spring 上下文访问 bean,然后调用 reload 方法来更新 bean 属性(因为单例)它也将在 spring 上下文中更新,并且在它自动装配/注入的任何地方。

Delete & Register Bean in Registry
You can use DefaultSingletonBeanRegistryto remove & re-register your bean. The only drawback to this, it will not refresh/reload old instance of already autowired/injected bean in consumer classes.

在注册表中删除和注册 Bean
您可以使用它DefaultSingletonBeanRegistry来删除和重新注册您的 bean。唯一的缺点是,它不会刷新/重新加载消费者类中已经自动装配/注入的 bean 的旧实例。

DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
registry.destroySingleton({yourbean}) //destroys the bean object
registry.registerSingleton({yourbeanname}, {newbeanobject}) //add to singleton beans cache

@RefreshScope
Useful for refreshing bean value properties from config changes. But it has very limited & specific purpose. Resourceto read more about it.

@RefreshScope
用于从配置更改刷新 bean 值属性。但它的用途非常有限且特定。阅读更多相关信息的资源